Metadata
Key | Value |
---|---|
engine | transformers |
prompt | completion |
temp | 0.2 |
top_p | 0.95 |
max_new_tokens | 1024 |
n_completions | 10 |
Solutions
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
func hasMissingPositive(numbers: [Int]) -> Int {
var i = 0
while i < numbers.count {
if numbers[i] > 0 && numbers[i] < numbers.count && numbers[i] != numbers[numbers[i] - 1] {
let temp = numbers[i]
numbers[i] = numbers[numbers[i] - 1]
numbers[temp - 1] = temp
} else {
i += 1
}
}
for i in 0..<numbers.count {
if numbers[i] != i + 1 {
return i + 1
}
}
return numbers.count + 1
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given an array of integers, find the first missing positive integer in linear time and constant space.
// In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// hasMissingPositive([3, 4, -1, 1]) == 2
// hasMissingPositive([1, 2, 0]) == 3
func hasMissingPositive(numbers: [Int]) -> Int {
var i = 0
while i < numbers.count {
if numbers[i] > 0 && numbers[i] < numbers.count && numbers[i] != numbers[numbers[i] - 1] {
let temp = numbers[i]
numbers[i] = numbers[numbers[i] - 1]
numbers[temp - 1] = temp
} else {
i += 1
}
}
for i in 0..<numbers.count {
if numbers[i] != i + 1 {
return i + 1
}
}
return numbers.count + 1
}
// -----------------------------------------------------------------------------
// 1.1.3
// Given an array of integers, find the first missing positive integer in linear time and constant space.
// In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// hasMissingPositive([3, 4, -1, 1]) == 2
// hasMissingPositive([1, 2, 0]) == 3
func hasMissingPositive(numbers: [Int]) -> Int {
var i = 0
while i < numbers.count {
if numbers[i] > 0 && numbers[i] < numbers.count && numbers[i] != numbers[numbers[i] - 1] {
let temp = numbers[i]
numbers[i] = numbers[numbers[i] - 1]
numbers[temp - 1] = temp
} else {
i += 1
}
}
for i in 0..<numbers.count {
if numbers[i] != i + 1 {
return i + 1
}
}
return numbers.count + 1
}
// -----------------------------------------------------------------------------
// 1.1.4
// Given an array of integers, find the first missing positive integer in linear time and constant space.
// In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// hasMissingPositive([3, 4, -1, 1]) == 2
// hasMissingPositive([1, 2, 0]) == 3
func hasMissingPositive(numbers: [Int]) -> Int {
var i = 0
while i < numbers.count {
if numbers[i] > 0 && numbers[i] < numbers.count &&
numbers[i] = numbers[numbers[i] - 1] // cannot assign through subscript: 'numbers' is a 'let' constant
numbers[temp - 1] = temp // cannot assign through subscript: 'numbers' is a 'let' constant
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, num1) in numbers.enumerate() {
for (j, num2) in numbers.enumerate() {
if i != j && abs(num1 - num2) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, num1) in numbers.enumerate() {
for (j, num2) in numbers.enumerate() {
if i != j && abs(num1 - num2) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
// ---------------------
for (i, num1) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
for (j, num2) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i == j {
continue
}
if abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i == j {
continue
}
if abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if isVowel(c) {
continue
}
result += c
}
return result
}
for (i, n1) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
for (j, n2) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
if isVowel(c) { // cannot find 'isVowel' in scope
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, first) in numbers.enumerate() {
for second in numbers[i+1...] {
if abs(first - second) < threshold {
return true
}
}
}
return false
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
func removeNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char
}
}
return result
}
func removeNonAlphabeticAndLowercase(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char.toLowercase()
}
}
return result
}
func removeNonAlphabeticAndUppercase(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char.toUpperCase()
}
}
return result
}
func reverseAndRemoveNonAlphabeticAndLowercase(input: String) -> String {
var result = ""
var words = input.split(" ")
for word in words {
var reversed = ""
for char in word {
if isAlphabetic(char) {
reversed = char + reversed
}
}
result += reversed + " "
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, first) in numbers.enumerate() {
for second in numbers[i+1...] {
if abs(first - second) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// non-alphabetic characters removed.
// removeNonAlphabetic("I have never seen a thin person drinking Diet Coke.") == " have nver seen a thn prsn drnkng Dt Ck."
func removeNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// non-alphabetic characters removed, and all characters converted to lowercase.
// removeNonAlphabeticAndLowercase("I have never seen a THIN person drinking Diet CKe.") == " hv nver seen a thin prsn drnkng dtcke."
func removeNonAlphabeticAndLowercase(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char.toLowercase()
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// non-alphabetic characters removed, and all characters converted to uppercase.
// removeNonAlphabeticAndUppercase("I have never seen a THIN person drinking Diet CKe.") == " Hv NVER SEEN A THN PRSN DRNKNG DTCE."
func removeNonAlphabeticAndUppercase(input: String) -> String {
var result = ""
for char in input {
if isAlphabetic(char) {
result += char.toUpperCase()
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// non-alphabetic characters removed, and all characters converted to lowercase,
// and all words reversed.
// reverseAndRemoveNonAlphabeticAndLowercase("I have never seen a THIN person drinking Diet CKe.") == ".ekD tnirp ecnetn a sihT evah uG"
func reverseAndRemoveNonAlphabeticAndLowercase(input: String) -> String {
var result = ""
var words = input.split(" ")
for word in words {
var reversed = ""
for char in word {
if isAlphabetic(char) {
reversed = char + reversed
}
}
result += reversed + " "
}
return result
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all
// non-alphabetic characters removed, and all characters converted to lowercase,
//
for (i, first) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if isAlphabetic(char) { // cannot find 'isAlphabetic' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if isAlphabetic(char) { // cannot find 'isAlphabetic' in scope
result += char.toLowercase() // value of type 'Character' has no member 'toLowercase'
if isAlphabetic(char) { // cannot find 'isAlphabetic' in scope
result += char.toUpperCase() // value of type 'Character' has no member 'toUpperCase'
var words = input.split(" ") // no exact matches in call to instance method 'split'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i == j {
continue
}
if abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i == j {
continue
}
if abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
//
for (i, n1) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
for (j, n2) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n) in numbers.enumerate() {
for (j, m) in numbers.enumerate() {
if i == j {
continue
}
if abs(n - m) < threshold {
return true
}
}
}
return false
}
func noVowels(input: String) -> String {
var result = ""
for c in input {
switch c {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
break
default:
result += c
}
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n) in numbers.enumerate() {
for (j, m) in numbers.enumerate() {
if i == j {
continue
}
if abs(n - m) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// the vowels removed.
// noVowels("I have never seen a thin person drinking Diet Coke on a scale
// that measures from 1 to 100.") == " hv nvr sn thn prsn drnkng Dt Ck on a scl
// tht msrfs frm 1 t 100."
func noVowels(input: String) -> String {
var result = ""
for c in input {
switch c {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
break
default:
result += c
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// the vowels removed.
// noVowels("I have never seen a thin person drinking Diet Coke on a scale
// that measures from 1 to 100.") == " hv nvr sn thn prsn drnkng Dt Ck on a scl
// tht msrfs frm 1 t 100."
func noVowels(input: String) -> String {
var result = ""
for c in input {
switch c {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
break
default:
result += c
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// the vowels removed.
// noVowels("I have never seen a thin person drinking Diet Coke on a scale
// that measures from 1 to 100.") == " hv nvr sn thn prsn drnkng Dt Ck on a scl
// tht msrfs frm 1 t 100."
func noVowels(input: String) -> String {
var result = ""
for c in input {
switch c {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
break
default:
result += c
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// the vowels removed.
// noVowels("I have never seen a thin person drinking Diet Coke on a scale
// that measures from 1 to 100.") == " hv nvr sn thn prsn drnkng Dt Ck on a scl
// tht msrfs frm 1 t 100."
func noVowels(input: String) -> String {
var result = ""
for c in input {
switch c {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
break
default:
result += c
}
}
return result
}
// ------------------------------------------------------------
for (i, n) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
for (j, m) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i != j && abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, n1) in numbers.enumerate() {
for (j, n2) in numbers.enumerate() {
if i != j && abs(n1 - n2) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
return result
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I love apples!") == " lv pp!"
func removeVowels(input: String) -> String {
var result = ""
for c in input {
if c.isVowel() {
continue
}
result += c
}
for (i, n1) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
for (j, n2) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
if c.isVowel() { // value of type 'Character' has no member 'isVowel'
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
func reverseOddIndices(string: String) -> String {
var result = ""
for i in 0..<string.count {
if i % 2 == 1 {
result += string[i]
} else {
result += string[string.count - i - 1]
}
}
return result
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func isPalindromeIgnoringNonAlphanumeric(string: String) -> Bool {
var result = ""
for char in string {
if char.isAlphanumeric() {
result += char.lowercase
}
}
return result == result.reversed().join()
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string as a parameter and returns a new string that is the reverse
// of the original.
// reverseString("abc") == "cba"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string as a parameter and returns true if the string is a palindrome,
// and false otherwise.
// isPalindrome("abba") == true
// isPalindrome("abc") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string as a parameter and returns a new string that contains the same
// characters that are in the original string, but with the characters at odd indices reversed.
// reverseOddIndices("abcdef") == "abfedc"
func reverseOddIndices(string: String) -> String {
var result = ""
for i in 0..<string.count {
if i % 2 == 1 {
result += string[i]
} else {
result += string[string.count - i - 1]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string as a parameter and returns a new string that contains the same
// characters as the original string, but with all the vowels removed.
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string as a parameter and returns true if the string is a palindrome,
// ignoring non-alphanumeric characters, and false otherwise.
// isPalindromeIgnoringNonAlphanumeric("A man, a plan, a canal: Panama.") == true
// isPalindromeIgnoringNonAlphanumeric("A man, a plan, a canal: Panama!") == false
func isPalindromeIgnoringNonAlphanumeric(string: String) -> Bool {
var result = ""
for char in string {
if char.isAlphanumeric() {
result += char.lowercase
}
}
return result == result.reversed().join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string as a parameter and returns a new string that contains the same
// characters as the original string
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string == string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
result += string[i] // no exact matches in call to subscript
result += string[string.count - i - 1] // no exact matches in call to subscript
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isAlphanumeric() { // value of type 'Character' has no member 'isAlphanumeric'
result += char.lowercase // value of type 'Character' has no member 'lowercase'
return result == result.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
if abs(numbers[i] - numbers[i + 1]) < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count - 1 {
if abs(numbers[i] - numbers[i + 1]) < threshold {
return true
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
// XCTAssertTrue failed
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, first) in numbers.enumerate() {
for second in numbers[i+1...] {
if abs(first - second) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for (i, first) in numbers.enumerate() {
for second in numbers[i+1...] {
if abs(first - second) < threshold {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.16
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.17
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.18
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.19
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.20
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.21
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.22
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.23
// -----------------------------------------------------------------------------
// ------------------------
for (i, first) in numbers.enumerate() { // value of type '[Double]' has no member 'enumerate'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var openBrackets = 0
for char in parenString {
if char == "(" {
openBrackets += 1
} else if char == ")" {
openBrackets -= 1
}
currentGroup += char
if openBrackets == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var openBrackets = 0
for char in parenString {
if char == "(" {
openBrackets += 1
} else if char == ")" {
openBrackets -= 1
}
currentGroup += char
if openBrackets == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
let parenString = parenString.trimmingCharacters(in: .whitespace)
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
currentGroup += "("
} else if char == ")" {
currentGroup += ")"
groups.append(currentGroup)
currentGroup = ""
} else {
currentGroup += char
}
}
return groups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
let parenString = parenString.trimmingCharacters(in: .whitespace)
var groups = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
currentGroup += "("
} else if char == ")" {
currentGroup += ")"
groups.append(currentGroup)
currentGroup = ""
} else {
currentGroup += char
}
}
return groups
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let parenString = parenString.trimmingCharacters(in: .whitespace) // type 'CharacterSet' has no member 'whitespace'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
for char in parenString {
if char == "(" {
current += "("
} else if char == ")" {
current += ")"
result.append(current)
current = ""
} else {
current += char
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
for char in parenString {
if char == "(" {
current += "("
} else if char == ")" {
current += ")"
result.append(current)
current = ""
} else {
current += char
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
if currentGroup != "" {
result.append(currentGroup)
currentGroup = ""
}
currentGroup += "("
} else if char == ")" {
currentGroup += ")"
if currentGroup.count > 1 {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup += char
}
}
if currentGroup != "" {
result.append(currentGroup)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
for char in parenString {
if char == "(" {
if currentGroup != "" {
result.append(currentGroup)
currentGroup = ""
}
currentGroup += "("
} else if char == ")" {
currentGroup += ")"
if currentGroup.count > 1 {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup += char
}
}
if currentGroup != "" {
result.append(currentGroup)
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var openBrackets = 0
for char in parenString {
if char == "(" {
openBrackets += 1
} else if char == ")" {
openBrackets -= 1
}
currentGroup += char
if openBrackets == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var openBrackets = 0
for char in parenString {
if char == "(" {
openBrackets += 1
} else if char == ")" {
openBrackets -= 1
}
currentGroup += char
if openBrackets == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var currentGroup = String()
for char in parenString {
if char == "(" {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
}
} else if char == ")" {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
result.append(currentGroup)
currentGroup = String()
}
} else {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
}
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var currentGroup = String()
for char in parenString {
if char == "(" {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
}
} else if char == ")" {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
result.append(currentGroup)
currentGroup = String()
}
} else {
if currentGroup.isEmpty {
result.append(String(char))
} else {
currentGroup += char
}
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
currentGroup += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
open -= 1
}
current += char
if open == 0 {
result.append(current)
current = ""
}
}
return result
}
func reverseString(string: String) -> String {
var result = ""
for char in string {
result = char + result
}
return result
}
func capitalizeFirst(string: String) -> String {
var result = ""
var first = true
for char in string {
if first {
result += char.uppercaseString
first = false
} else {
result += char.lowercaseString
}
}
return result
}
func removeSpaces(string: String) -> String {
var result = ""
for char in string {
if char != " " {
result += char
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
open -= 1
}
current += char
if open == 0 {
result.append(current)
current = ""
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
var result = ""
for char in string {
result = char + result
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string as input and returns the string with the first letter capitalized and the rest lowercase.
// capitalizeFirst("hello") == "Hello"
// capitalizeFirst("sHoRt AnD sToUt") == "Short And Stout"
func capitalizeFirst(string: String) -> String {
var result = ""
var first = true
for char in string {
if first {
result += char.uppercaseString
first = false
} else {
result += char.lowercaseString
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string as input and returns the string with all the spaces removed,
// leaving only the original string's separators (e.g. spaces, commas, periods, etc.).
// removeSpaces("Hello, world!") == "Helloworld!"
// removeSpaces("Hi, my name is John.") == "Hi,mynameisJohn."
func removeSpaces(string: String) -> String {
var result = ""
for char in string {
if char != " " {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string as input and returns the string with all the spaces removed,
// leaving only the original string's separators (e.g. spaces, commas, periods, etc.).
// removeSpaces("Hello, world!") == "Helloworld!"
// removeSpaces("Hi, my name is John.") == "Hi,mynameisJohn."
func removeSpaces(string: String) -> String {
var result = ""
for char in string {
if char != " " {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string as input and returns the string with all the spaces removed,
// leaving only the original string's separators (e.g. spaces, commas, periods, etc.).
// removeSpaces("Hello, world!") == "Helloworld!"
// removeSpaces("Hi, my name is John.") == "Hi,mynameisJohn."
func removeSpaces(string: String) -> String {
var result = ""
for char in string {
if char != " " {
result += char
}
}
return result
current += char // cannot convert value of type 'Character' to expected argument type 'String'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var current = String()
for char in parenString {
if char == "(" {
current += "("
result.append(current)
current = String()
} else if char == ")" {
current += ")"
result.append(current)
current = String()
} else {
current += char
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var current = String()
for char in parenString {
if char == "(" {
current += "("
result.append(current)
current = String()
} else if char == ")" {
current += ")"
result.append(current)
current = String()
} else {
current += char
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var current = String()
for char in parenString {
if char == "(" {
if current != "" {
result.append(current)
current = ""
}
result.append("(")
} else if char == ")" {
if current != "" {
result.append(current)
current = ""
}
result.append(")")
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String()]
var current = String()
for char in parenString {
if char == "(" {
if current != "" {
result.append(current)
current = ""
}
result.append("(")
} else if char == ")" {
if current != "" {
result.append(current)
current = ""
}
result.append(")")
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current += char
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var open = 0
var close = 0
for char in parenString {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
current += char
if open == close {
result.append(current)
current = ""
open = 0
close = 0
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a string with the first
// character capitalized.
// capitalizeFirst("hello") == "Hello"
func capitalizeFirst(string: String) -> String {
return string.first!.uppercaseString + string.substring(1)
}
// ---------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
return string.first!.uppercaseString + string.substring(1) // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
return string.first!.uppercaseString + string.substring(1) // no exact matches in call to instance method 'substring'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (lef
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 1.7
// ------------------------------------------------------------------------
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Int(number)
}
// -----------------------------------------------------------------------------
// 2. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 3. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 4. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 5. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 6. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 7. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 8. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// -----------------------------------------------------------------------------
// 9. Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// ---
return number - Int(number) // cannot convert value of type 'Int' to expected argument type 'Double'
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// 11. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 12. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 13. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 14. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 15. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 16. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijkl
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func countVowels(input: String) -> Int {
var vowels = 0
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
result += char
}
return result
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// 2. Write a function that takes a string and returns the number (count) of vowels contained in it.
// Valid vowels are: a, e, i, o, u.
// countVowels("abracadabra") == 5
// countVowels("pear tree") == 5
// countVowels("o a kak ushakov lil vo kashu kakao") == 12
// countVowels("harvey") == 4
func countVowels(input: String) -> Int {
var vowels = 0
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
// 3. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdrvbr"
// removeVowels("pear tree") == "pr t"
// removeVowels("o a kak ushakov lil vo kashu kakao") == " kv kv kv"
// removeVowels("harvey") == "hrv"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
result += char
}
return result
}
// 4. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdrvbr"
// removeVowels("pear tree") == "pr t"
// removeVowels("o a kak ushakov lil vo kashu kakao") == " kv kv kv"
// removeVowels("harvey") == "hrv"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
result += char
}
return result
}
// 5. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdrvbr"
// removeVowels("pear tree") == "pr t"
// removeVowels("o a kak ushakov lil vo kashu kakao") == " kv kv kv"
// removeVowels("harvey") == "hrv"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
result += char
}
return result
}
// 6. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnk
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func reverseString(string: String) -> String {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed
}
func countDigits(number: Int) -> Int {
var count = 0
while number > 0 {
number /= 10
count += 1
}
return count
}
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// 12. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed
}
// 13. Write a function that takes a number as input and returns the number of digits in the
// number.
// countDigits(123) == 3
func countDigits(number: Int) -> Int {
var count = 0
while number > 0 {
number /= 10
count += 1
}
return count
}
// 14. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 15. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 16. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 17. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 18. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 19. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 20. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 21. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) == 6
func sumDigits(number: Int) -> Int {
var sum = 0
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// 22. Write a function that takes a number as input and returns the sum of the digits in the
// number.
// sumDigits(123) ==
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
number /= 10 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number /= 10 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
return output
}
// ------------------------------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I am awesome!") == " m wmn !"
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if !isVowel(char) {
output += char
}
}
if !isVowel(char) { // cannot find 'isVowel' in scope
output += char // cannot convert value of type 'Character' to expected argument type 'String'
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// 2. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// ------------------------------------------------------------------------------------------------
// 1. You can modify the input array in-place.
// 2. You can use extra space.
// 3. You can sort the array.
// 4. You can use extra space.
// 5. You can sort the array.
// 6. You can sort the array.
// 7. You can sort the array.
// 8. You can sort the array.
// 9. You can sort the array.
// 10. You can sort the array.
// 11. You can sort the array.
// 12. You can sort the array.
// 13. You can sort the array.
// 14. You can sort the array.
// 15. You can sort the array.
// 16. You can sort the array.
// 17. You can sort the array.
// 18. You can sort the array.
// 19. You can sort the array.
// 20. You can sort the array.
// 21. You can sort the array.
// 22. You can sort the array.
// 23. You can sort the array.
// 24. You can sort the array.
// 25. You can sort the array.
// 26. You can sort the array.
// 27. You can sort the array.
// 28. You can sort the array.
// 29. You can sort the array.
// 30. You can sort the array.
// 31. You can sort the array.
// 32. You can sort the array.
// 33. You can sort the array.
// 34. You can sort the array.
// 35. You can sort the array.
// 36. You can sort the array.
// 37. You can sort the array.
// 38. You can sort the array.
// 39. You can sort the array.
// 40. You can sort the array.
// 41. You can sort the array.
// 42. You can sort the array.
// 43. You can sort the array.
// 44. You can sort the array.
// 45. You can sort the array.
// 46. You can sort the array.
// 47. You can sort the array.
// 48. You can sort the array.
// 49. You can sort the array.
// 50. You can sort the array.
// 51. You can sort the array.
// 52. You can sort the array.
// 53. You can sort the array.
// 54. You can sort the array.
// 55. You can sort the array.
// 56. You can sort the array.
// 57. You can sort the array.
// 58. You can sort the array.
// 59. You can sort the array.
// 60. You can sort the array.
// 61. You can sort the array.
// 62. You can sort the array.
// 63. You can sort the array.
// 64. You can sort the array.
// 65. You can sort the array.
// 66. You can sort the array.
// 67. You can sort the array.
//
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func firstMissingPositive(numbers: [Int]) -> Int {
var i = 1
while true {
if !numbers.contains(i) {
return i
}
i += 1
}
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// 2. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func firstMissingPositive(numbers: [Int]) -> Int {
var i = 1
while true {
if !numbers.contains(i) {
return i
}
i += 1
}
}
// 3. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func firstMissingPositive(numbers: [Int]) -> Int {
var i = 1
while true {
if !numbers.contains(i) {
return i
}
i += 1
}
}
// 4. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func firstMissingPositive(numbers: [Int]) -> Int {
var i = 1
while true {
if !numbers.contains(i) {
return i
}
i += 1
}
}
// 5. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func firstMissingPositive(numbers: [Int]) -> Int {
var i = 1
while true {
if !numbers.contains(i) {
return i
}
i += 1
}
}
// 6. Given an array of integers, find the first missing positive integer in linear time and constant
// space. In other words, find the lowest positive integer that does not exist in the array.
// The array can contain duplicates and negative numbers as well.
// For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
// You can modify the input array in-place.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func firstMissingPositive(numbers
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, element: Double) -> Double in
return sum + element
}) / numbers.count
let deviations = numbers.map { (x: Double) -> Double in
return abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum: Double, element: Double) -> Double in
return sum + element
}) / deviations.count
return mad
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, element: Double) -> Double in
return sum + element
}) / numbers.count
let deviations = numbers.map { (x: Double) -> Double in
return abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum: Double, element: Double) -> Double in
return sum + element
}) / deviations.count
return mad
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ------------------------
}) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
let deviations = numbers.map { x in
abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
return mad
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
let deviations = numbers.map { x in
abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
return mad
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
}) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.mean()
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
return absDeviations.mean()
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.mean()
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
return absDeviations.mean()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
let mean = numbers.mean() // value of type '[Double]' has no member 'mean'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / numbers.count
let deviations = numbers.map { $0 - mean }
return deviations.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + abs(x)
} }) / numbers.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / numbers.count
let deviations = numbers.map { $0 - mean }
return deviations.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + abs(x)
} }) / numbers.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------------
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double { // expected type after '->'
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double { // contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored
return sum + x // cannot find 'sum' in scope
return sum + x // cannot find 'x' in scope
} }) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
return deviations.reduce(0.0, { (sum: Double, x: Double) -> Double { // expected type after '->'
return sum + abs(x) // cannot find 'x' in scope
return sum + abs(x) // cannot find 'sum' in scope
} }) / numbers.count // no '/' candidates produce the expected contextual result type 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / numbers.count
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
return absDeviations.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / absDeviations.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / numbers.count
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
return absDeviations.reduce(0.0, { (sum: Double, x: Double) -> Double {
return sum + x
} }) / absDeviations.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double { // expected type after '->'
let mean = numbers.reduce(0.0, { (sum: Double, x: Double) -> Double { // contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored
return sum + x // cannot find 'sum' in scope
return sum + x // cannot find 'x' in scope
} }) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
return absDeviations.reduce(0.0, { (sum: Double, x: Double) -> Double { // expected type after '->'
return sum + x // cannot find 'sum' in scope
return sum + x // cannot find 'x' in scope
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, element) -> Double in
return sum + element
}) / numbers.count
let deviations = numbers.map { (element) -> Double in
return abs(element - mean)
}
return deviations.reduce(0.0, { (sum, element) -> Double in
return sum + element
}) / numbers.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, element) -> Double in
return sum + element
}) / numbers.count
let deviations = numbers.map { (element) -> Double in
return abs(element - mean)
}
return deviations.reduce(0.0, { (sum, element) -> Double in
return sum + element
}) / numbers.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
}) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
}) / numbers.count // no '/' candidates produce the expected contextual result type 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
let deviations = numbers.map { x in
abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
return mad
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
let deviations = numbers.map { x in
abs(x - mean)
}
let mad = deviations.reduce(0.0, { (sum, x) -> Double in
sum + x
}) / numbers.count
return mad
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
}) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
let sum = absDeviations.reduce(0.0, { $0 + $1 })
return sum / absDeviations.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
let deviations = numbers.map { $0 - mean }
let absDeviations = deviations.map { abs($0) }
let sum = absDeviations.reduce(0.0, { $0 + $1 })
return sum / absDeviations.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
let deviations = numbers.map { $0 - mean }
return deviations.map { abs($0) }.reduce(0.0, { $0 + $1 }) / numbers.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
let deviations = numbers.map { $0 - mean }
return deviations.map { abs($0) }.reduce(0.0, { $0 + $1 }) / numbers.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count // binary operator '/' cannot be applied to operands of type 'Double' and 'Int'
return deviations.map { abs($0) }.reduce(0.0, { $0 + $1 }) / numbers.count // no '/' candidates produce the expected contextual result type 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
return numbers.map { $0 - mean }.map { abs($0) }.reduce(0.0, { $0 + $1 }) / numbers.count
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, { $0 + $1 }) / numbers.count
return numbers.map { $0 - mean }.map { abs($0) }.reduce(0.0, { $0 + $1 }) / numbers.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.10
// Given an array of integers, find the largest sum of any contiguous subarray.
// Example:
// [1, -2, 3, 4, -5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4,
// Fatal error: Can't remove last element from an empty collection
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are 'a', 'e', 'i', 'o', and 'u'.
// vowelFree("Hello world") == "Hll wrld"
// vowelFree("") == ""
// vowelFree("a") == ""
// vowelFree("aeiou") == ""
// vowelFree("aeiouAEIOU") == ""
// vowelFree("aeiouAEIOU12345") == "12345"
// vowelFree("aeiouAEIOU12345aeiouAEIOU12345") == "1234512345"
// vowelFree("aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345") == "123451234512345"
// vowelFree("aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345") == "12345123451234512345"
// vowelFree("aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345") == "123451234512345123451234512345"
// vowelFree("aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU12345aeiouAEIOU
// Fatal error: Can't remove last element from an empty collection
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
if result.count > 0 {
result.removeLast()
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
if result.count > 0 {
result.removeLast()
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
result.removeLast()
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Can't remove last element from an empty collection
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.append(delimeter)
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.append(delimeter)
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func firstUniqChar(s: String) -> Int {
var dict = [Int: Int]()
for i in s {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i]! + 1
}
}
for i in s {
if dict[i] == 1 {
return s.firstIndex(of: i)!
}
}
return -1
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.11
// ---------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ---------------------------------------------------------------------------------------------------------------------
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.12
// ---------------------------------------------------------------------------------------------------------------------
// Given a string s, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// ---------------------------------------------------------------------------------------------------------------------
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var dict = [Int: Int]()
for i in s {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i]! + 1
}
}
for i in s {
if dict[i] == 1 {
return s.firstIndex(of: i)!
}
}
return -1
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.13
// ---------------------------------------------------------------------------------------------------------------------
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Example 1:
// Input: "A man, a plan, a canal: Panama"
// Output: true
// Example 2:
// Input: "race a car"
// Output: false
// ---------------------------------------------------------------------------------------------------------------------
// isPalindrome("A man, a plan, a canal: Panama") == true
// isPalindrome("race a car") == false
func isPalindrome(s: String) -> Bool {
var s = s.trimmingCharacters(in: .whitespaceAndNewline)
s = s.replacingOccurrences(of: " ", with: "")
s = s.replacingOccurrences(of: ",", with: "")
s = s.replacingOccurrences(of: ":", with: "")
s = s.replacingOccurrences(of: ";", with: "")
s = s.replacingOccurrences(of:
if dict[i] == nil { // cannot convert value of type 'Character' to expected argument type 'Int'
dict[i] = 1 // cannot convert value of type 'Character' to expected argument type 'Int'
dict[i] = dict[i]! + 1 // cannot convert value of type 'Character' to expected argument type 'Int'
dict[i] = dict[i]! + 1 // cannot convert value of type 'Character' to expected argument type 'Int'
if dict[i] == 1 { // cannot convert value of type 'Character' to expected argument type 'Int'
return s.firstIndex(of: i)! // cannot convert return expression of type 'String.Index' to return type 'Int'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
if result.count > 0 {
result.removeLast()
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
if result.count > 0 {
result.removeLast()
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
func longestSubstring(s: String) -> Int {
var result = 0
var current = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = i
current += 1
} else {
result = max(result, current)
current = i - map[s[i]]
map.remove(key: s[i])
}
}
return max(result, current)
}
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var current = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = i
current += 1
} else {
result = max(result, current)
current = i - map[s[i]]
map.remove(key: s[i])
}
}
return max(result, current)
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for i in numbers {
result.append(i)
result.append(delimeter)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2
// ----------------------------------------------------------------------------------------------------------------------
// Given a string `s`, return the length of the longest substring without repeating characters.
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var result = 0
var current = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = i
current += 1
} else {
result = max(result, current)
current = i - map[s[i]]
map.remove(key: s[i])
}
}
return max(result, current)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// ----------------------------------------------------------------------------------------------------------------------
// Given a string `s`, find the length of the longest substring without repeating characters.
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var current = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = i
current += 1
} else {
result = max(result, current)
current = i - map[s[i]]
map.remove(key: s[i])
}
}
return max(result, current)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// ----------------------------------------------------------------------------------------------------------------------
// Given a string `s`, find the length of the longest substring without repeating characters.
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var current = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = i
current += 1
} else {
result = max(result, current)
current = i - map[s[i]]
map.remove(key: s[i])
}
}
return max(result, current)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.5
// ---------------------------
if map[s[i]] == nil { // cannot convert value of type 'Character' to expected argument type 'Int'
map[s[i]] = i // cannot convert value of type 'Character' to expected argument type 'Int'
current = i - map[s[i]] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
current = i - map[s[i]] // cannot convert value of type 'Character' to expected argument type 'Int'
map.remove(key: s[i]) // incorrect argument label in call (have 'key:', expected 'at:')
map.remove(key: s[i]) // cannot convert value of type 'Character' to expected argument type 'Dictionary<Int, Int>.Index'
if map[s[i]] == nil { // cannot convert value of type 'Character' to expected argument type 'Int'
map[s[i]] = i // cannot convert value of type 'Character' to expected argument type 'Int'
current = i - map[s[i]] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
current = i - map[s[i]] // cannot convert value of type 'Character' to expected argument type 'Int'
map.remove(key: s[i]) // cannot convert value of type 'Character' to expected argument type 'Dictionary<Int, Int>.Index'
map.remove(key: s[i]) // incorrect argument label in call (have 'key:', expected 'at:')
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
result.append(currentLevel)
currentLevel -= 1
}
}
return result
}
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
result.append(currentLevel)
currentLevel -= 1
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "Hello World") == "Hll Wrld"
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "Hello World") == "Hll Wrld"
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "Hello World") == "Hll Wrld"
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "Hello World") == "Hll Wrld"
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "Hello World") == "Hll Wrld"
func removeVowels(inputString: String) -> String {
var result = ""
for char in inputString {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ---------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for c in parenString {
if c == "(" {
currentLevel += 1
} else if c == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for c in parenString {
if c == "(" {
currentLevel += 1
} else if c == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "This is a test string") == "Ths s tst strng"
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "This is a test string") == "Ths s tst strng"
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "This is a test string") == "Ths s tst strng"
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "This is a test string") == "Ths s tst strng"
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(inputString: "This is a test string") == "Ths s tst strng"
func removeVowels(inputString: String) -> String {
var result = ""
for c in inputString {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
for c in parenString {
switch c {
case "(":
level += 1
case ")":
level -= 1
default:
result.append(level)
}
}
return result
}
func longestSubstring(s: String) -> String {
var result = ""
var current = ""
var lastSeen = ""
for c in s {
if lastSeen.contains(c) {
if current.length > result.length {
result = current
}
current = ""
}
current += c
lastSeen = c
}
if current.length > result.length {
result = current
}
return result
}
func longestRepeating(s: String) -> String {
var result = ""
var current = ""
var lastSeen = ""
for c in s {
if lastSeen.contains(c) {
current += c
} else {
if current.length > result.length {
result = current
}
current = ""
}
lastSeen = c
}
if current.length > result.length {
result = current
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
for c in parenString {
switch c {
case "(":
level += 1
case ")":
level -= 1
default:
result.append(level)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.1
// -----------------------------------------------------------------------------
// Given a string, output the longest substring with no repeating characters.
// E.g. longestSubstring("abcabcbb") == "abc"
// longestSubstring("bbbbb") == "b"
// longestSubstring("pwwkew") == "wke"
// longestSubstring("") == ""
// longestSubstring("aab") == "aab"
// longestSubstring("dvdf") == "vdf"
func longestSubstring(s: String) -> String {
var result = ""
var current = ""
var lastSeen = ""
for c in s {
if lastSeen.contains(c) {
if current.length > result.length {
result = current
}
current = ""
}
current += c
lastSeen = c
}
if current.length > result.length {
result = current
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given a string, output the longest substring with repeating characters.
// E.g. longestRepeating("abcabcbb") == "abc"
// longestRepeating("bbbbb") == "b"
// longestRepeating("pwwkew") == "wke"
// longestRepeating("") == ""
// longestRepeating("aab") == "aab"
// longestRepeating("dvdf") == "vdf"
func longestRepeating(s: String) -> String {
var result = ""
var current = ""
var lastSeen = ""
for c in s {
if lastSeen.contains(c) {
current += c
} else {
if current.length > result.length {
result = current
}
current = ""
}
lastSeen = c
}
if current.length > result.length {
result = current
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given a string, output the longest substring with repeating characters.
// E.g. longestRepeating("abcabcbb") == "abc"
// longestRepeating("bbbbb") == "b"
// longestRepeating("pwwkew") == "wke"
// longestRepeating("") == ""
// longestRepeating("aab") == "aab"
// longestRepeating("dvdf") == "vdf"
func longestRepeating(s: String) -> String {
var result = ""
var current = ""
var lastSeen = ""
var lastSeenIndex = 0
for i in 0..<s.length {
if lastSeen.contains(s[i]) {
if current.length > result.length {
result = current
}
current = ""
lastSeenIndex = i
} else {
current += s[i]
}
lastSeen = s[i]
}
if
if current.length > result.length { // value of type 'String' has no member 'length'
if current.length > result.length { // value of type 'String' has no member 'length'
current += c // cannot convert value of type 'Character' to expected argument type 'String'
lastSeen = c // cannot assign value of type 'Character' to type 'String'
if current.length > result.length { // value of type 'String' has no member 'length'
if current.length > result.length { // value of type 'String' has no member 'length'
current += c // cannot convert value of type 'Character' to expected argument type 'String'
if current.length > result.length { // value of type 'String' has no member 'length'
if current.length > result.length { // value of type 'String' has no member 'length'
lastSeen = c // cannot assign value of type 'Character' to type 'String'
if current.length > result.length { // value of type 'String' has no member 'length'
if current.length > result.length { // value of type 'String' has no member 'length'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 18. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 19. Write a function that takes a string and returns the longest palindromic substring.
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.append(stack.pop() + 1)
}
}
return stack
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.append(stack.pop() + 1)
}
}
return stack
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------
stack.append(stack.pop() + 1) // value of type '[Int]' has no member 'pop'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.4
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.6
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.7
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.8
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.9
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.10
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.11
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
stack.append(currentLevel)
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
result.append(stack.pop())
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
stack.append(currentLevel)
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
result.append(stack.pop())
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------
result.append(stack.pop()) // value of type '[Int]' has no member 'pop'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.append(stack.pop() + 1)
}
}
return stack
}
func longestSubstringWithoutRepeatingChars(s: String) -> String {
var result = ""
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
if stack.count > result.count {
result = String(stack)
}
}
return result
}
func longestSubstringWithoutRepeatingChars(s: String) -> Int {
var result = 0
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
result = max(result, stack.count)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.append(stack.pop() + 1)
}
}
return stack
}
// 2. Given a string, return the longest substring without repeating characters.
// For example, the longest substrings without repeating characters for "abcabcbb" is "abc",
// which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
// For "pwwkew", the longest substring is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// longestSubstringWithoutRepeatingChars(s: "abcabcbb") == "abc"
// longestSubstringWithoutRepeatingChars(s: "bbbbb") == "b"
// longestSubstringWithoutRepeatingChars(s: "pwwkew") == "wke"
func longestSubstringWithoutRepeatingChars(s: String) -> String {
var result = ""
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
if stack.count > result.count {
result = String(stack)
}
}
return result
}
// 3. Given a string s, find the length of the longest substring without repeating characters.
// s = "abcabcbb"
// longestSubstringWithoutRepeatingChars(s: "abcabcbb") == 3
// s = "bbbbb"
// longestSubstringWithoutRepeatingChars(s: "bbbbb") == 1
// s = "pwwkew"
// longestSubstringWithoutRepeatingChars(s: "pwwkew") == 3
func longestSubstringWithoutRepeatingChars(s: String) -> Int {
var result = 0
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
result = max(result, stack.count)
}
return result
}
// 4. Given a string s, find the length of the longest substring without repeating characters.
// s = "abcabcbb"
// longestSubstringWithoutRepeatingChars(s: "abcabcbb") == 3
// s = "bbbbb"
// longestSubstringWithoutRepeatingChars(s: "bbbbb") == 1
// s = "pwwkew"
// longestSubstringWithoutRepeatingChars(s: "pwwkew") == 3
func longestSubstringWithoutRepeatingChars(s: String) -> Int {
var result = 0
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
result = max(result, stack.count)
}
return result
}
// 5. Given a string s, find the length of the longest substring without repeating characters.
// s = "abcabcbb"
// longestSubstringWithoutRepeatingChars(s: "abcabcbb") == 3
// s = "bbbbb"
// longestSubstringWithoutRepeatingChars(s: "bbbbb") == 1
// s = "pwwkew"
// longestSubstringWithoutRepeatingChars(s: "pwwkew") == 3
func longestSubstringWithoutRepeatingChars(s: String) -> Int {
var result = 0
var stack = [String]()
for char in s {
if stack.contains(char) {
stack = []
}
stack.append(char)
result = max(result, stack.count)
}
return result
}
// 6. Given a string s, find the length
stack.append(stack.pop() + 1) // value of type '[Int]' has no member 'pop'
if stack.contains(char) { // cannot convert value of type 'Character' to expected argument type 'String'
stack.append(char) // cannot convert value of type 'Character' to expected argument type 'String'
result = String(stack) // no exact matches in call to initializer
if stack.contains(char) { // cannot convert value of type 'Character' to expected argument type 'String'
stack.append(char) // cannot convert value of type 'Character' to expected argument type 'String'
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.pop()
result.append(stack.count)
}
}
return result
}
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > result.count {
result = sub
}
}
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var stack = [Int]()
for char in parenString {
if char == "(" {
stack.append(1)
} else if char == ")" {
stack.pop()
result.append(stack.count)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2
// Given a string, return the longest palindromic substring in it.
// E.g. longestPalindrome("abaxyzzyxf") == "xyzzyx"
// longestPalindrome("abaxyzzyxf") == "xyzzyx"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > result.count {
result = sub
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.3
// Given a string, return the longest palindromic substring in it.
// E.g. longestPalindrome("abaxyzzyxf") == "xyzzyx"
// longestPalindrome("abaxyzzyxf") == "xyzzyx"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > result.count {
result = sub
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.4
// Given a string, return the longest palindromic substring in it.
// E.g. longestPalindrome("abaxyzzyxf") == "xyzzyx"
// longestPalindrome("abaxyzzyxf") == "xyzzyx"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > result.count {
result = sub
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.5
// Given a string, return the longest palindromic substring in it.
// E.g. longestPalindrome("abaxyzzyxf") == "xyzzyx"
// longestPalindrome("abaxyzzyxf") == "xyzzyx"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > result.count {
result = sub
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.6
// Given a string, return the longest palindromic substring in it.
// E.g. longestPalindrome("abaxyzzyxf") == "xyzzyx"
// longestPalindrome("abaxyzzyxf") == "xyzzyx"
func longest
stack.pop() // value of type '[Int]' has no member 'pop'
var sub = s[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if sub == sub.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
for char in parenString {
if char == "(" {
currentLevel += 1
} else if char == ")" {
currentLevel -= 1
}
result.append(currentLevel)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func sumIntegers(integers: [Int]) -> Int {
return integers.reduce(0, { $0 + $1 })
}
func average(integers: [Int]) -> Int {
return sumIntegers(integers) / integers.count
}
func max(integers: [Int]) -> Int {
return integers.max()!
}
func min(integers: [Int]) -> Int {
return integers.min()!
}
func diff(integers: [Int]) -> Int {
return max(integers) - min(integers)
}
func countEven(integers: [Int]) -> Int {
return integers.count(predicate: { $0 % 2 == 0 })
}
func countOdd(integers: [Int]) -> Int {
return integers.count(predicate: { $0 % 2 != 0 })
}
func countGreaterThanAverage(integers: [Int]) -> Int {
return integers.count(predicate: { $0 > average(integers) })
}
func countLessThanAverage(integers: [Int]) -> Int {
return integers.count(predicate: { $0 < average(integers) })
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// 2. Write a function that takes an array of integers and returns the sum of all the integers.
// sumIntegers([1, 2, 3]) == 6
// sumIntegers([1, 2, 3, 4, 5]) == 15
func sumIntegers(integers: [Int]) -> Int {
return integers.reduce(0, { $0 + $1 })
}
// 3. Write a function that takes an array of integers and returns the average of all the integers.
// average([1, 2, 3]) == 2
// average([1, 2, 3, 4, 5]) == 3
func average(integers: [Int]) -> Int {
return sumIntegers(integers) / integers.count
}
// 4. Write a function that takes an array of integers and returns the maximum value in the array.
// max([1, 2, 3]) == 3
// max([1, 2, 3, 4, 5]) == 5
func max(integers: [Int]) -> Int {
return integers.max()!
}
// 5. Write a function that takes an array of integers and returns the minimum value in the array.
// min([1, 2, 3]) == 1
// min([1, 2, 3, 4, 5]) == 1
func min(integers: [Int]) -> Int {
return integers.min()!
}
// 6. Write a function that takes an array of integers and returns the difference between the maximum and minimum values in the array.
// diff([1, 2, 3]) == 2
// diff([1, 2, 3, 4, 5]) == 4
func diff(integers: [Int]) -> Int {
return max(integers) - min(integers)
}
// 7. Write a function that takes an array of integers and returns the number of even integers in the array.
// countEven([1, 2, 3]) == 1
// countEven([1, 2, 3, 4, 5]) == 2
func countEven(integers: [Int]) -> Int {
return integers.count(predicate: { $0 % 2 == 0 })
}
// 8. Write a function that takes an array of integers and returns the number of odd integers in the array.
// countOdd([1, 2, 3]) == 1
// countOdd([1, 2, 3, 4, 5]) == 2
func countOdd(integers: [Int]) -> Int {
return integers.count(predicate: { $0 % 2 != 0 })
}
// 9. Write a function that takes an array of integers and returns the number of integers that are greater than the average of the integers in the array.
// countGreaterThanAverage([1, 2, 3]) == 0
// countGreaterThanAverage([1, 2, 3, 4, 5]) == 2
func countGreaterThanAverage(integers: [Int]) -> Int {
return integers.count(predicate: { $0 > average(integers) })
}
// 10. Write a function that takes an array of integers and returns the number of integers that are less than the average of the integers in the array.
// countLessThanAverage([1, 2, 3]) == 0
// countLessThanAverage([1, 2, 3, 4, 5]) == 3
func countLessThanAverage(integers: [Int]) -> Int {
return integers.count(predicate: { $0 < average(integers) })
}
// 11. Write a function that takes an array of integers and returns the number of integers that are between 10 and 20 (inclusive).
// countBetween10And20([1, 2, 3]) == 0
// countBetween10And20([1, 2, 3, 4, 5]) == 1
func countBetween10And20(integers: [Int]) -> Int {
return integers.count(predicate:
return sumIntegers(integers) / integers.count // missing argument label 'integers:' in call
return max(integers) - min(integers) // missing argument label 'integers:' in call
return max(integers) - min(integers) // missing argument label 'integers:' in call
return integers.count(predicate: { $0 % 2 == 0 }) // cannot call value of non-function type 'Int'
return integers.count(predicate: { $0 % 2 != 0 }) // cannot call value of non-function type 'Int'
return integers.count(predicate: { $0 > average(integers) }) // cannot call value of non-function type 'Int'
return integers.count(predicate: { $0 > average(integers) }) // missing argument label 'integers:' in call
return integers.count(predicate: { $0 < average(integers) }) // missing argument label 'integers:' in call
return integers.count(predicate: { $0 < average(integers) }) // cannot call value of non-function type 'Int'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterBySubstrings(strings: [String], substrings: [String]) -> [String] {
return strings.filter { $0.contains(substrings) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and an array of strings as input and returns a new array containing only the strings from the original array that do not contain any of the substrings in the second array.
// filterBySubstrings(strings: [] as [String], substrings: []) == [] as [String]
// filterBySubstrings(strings: ["abc", "bacd", "cde", "array"], substrings: ["a", "b"]) == ["cde"]
func filterBySubstrings(strings: [String], substrings: [String]) -> [String] {
return strings.filter { $0.contains(substrings) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and an array of strings as input and returns a new array containing only the strings from the original array that contain all of the substrings in the second array.
// filterBySubstrings(strings: [] as [String], substrings: []) == [] as [String]
// filterBySubstrings(strings: ["abc", "bacd", "cde", "array"], substrings: ["a", "b"]) == ["abc", "bacd"]
func filterBySubstrings(strings: [String], substrings: [String]) -> [String] {
return strings.filter { $0.contains(substrings) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and an array of strings as input and returns a new array containing only the strings from the original array that contain all of the substrings in the second array, in the order in which they appear in the second array.
// filterBySubstrings(strings: [] as [String], substrings: []) == [] as [String]
// filterBySubstrings(strings: ["abc", "bacd", "cde", "array"], substrings: ["a", "b"]) == ["abc", "bacd"]
func filterBySubstrings(strings: [String], substrings: [String]) -> [String] {
return strings.filter { $0.contains(substrings) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and an array of strings as input and returns a new array containing only the strings from the original array that contain all of the substrings in the second array, in the order in which they appear in the second array, and in the order in which they appear in the original array.
// filterBySubstrings(strings: [] as [String], substrings: []) == [] as [String]
// filterBySubstrings(strings: ["abc", "bacd", "cde", "array"], substrings: ["a", "b"]) == ["abc", "bacd"]
func filterBySubstrings(strings: [String], substrings: [String]) -> [String] {
return strings.filter { $0.contains(substrings) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string and an array of strings as input and returns a new array containing only the strings from the original array that contain all of the substrings in the second array, in the order in which they appear in the original array.
// filterBySubstrings(strings: [] as [String], substrings: []) == [] as [String]
// filterBySubstrings(strings:
return strings.filter { $0.contains(substrings) } // type of expression is ambiguous without a type annotation
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func sumIntegers(integers: [Int]) -> Int {
return integers.reduce(0, { $0 + $1 })
}
func sumOddIntegers(integers: [Int]) -> Int {
return integers.filter { $0 % 2 != 0 }.reduce(0, { $0 + $1 })
}
func sumEvenIntegers(integers: [Int]) -> Int {
return integers.filter { $0 % 2 == 0 }.reduce(0, { $0 + $1 })
}
func sumOddIntegersLessThan100(integers: [Int]) -> Int {
return integers.filter { $0 % 2 != 0 && $0 < 100 }.reduce(0, { $0 + $1 })
}
func sumEvenIntegersLessThan100(integers: [Int]) -> Int {
return integers.filter { $0 % 2 == 0 && $0 < 100 }.reduce(0, { $0 + $1 })
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes an array of integers and returns the sum of all the integers.
// sumIntegers([1, 2, 3, 4, 5]) == 15
// sumIntegers([-1, 2, 3, 4, 5]) == 12
// sumIntegers([]) == 0
func sumIntegers(integers: [Int]) -> Int {
return integers.reduce(0, { $0 + $1 })
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes an array of integers and returns the sum of all the integers that are odd.
// sumOddIntegers([1, 2, 3, 4, 5]) == 9
// sumOddIntegers([-1, 2, 3, 4, 5]) == 9
// sumOddIntegers([]) == 0
func sumOddIntegers(integers: [Int]) -> Int {
return integers.filter { $0 % 2 != 0 }.reduce(0, { $0 + $1 })
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes an array of integers and returns the sum of all the integers that are even.
// sumEvenIntegers([1, 2, 3, 4, 5]) == 10
// sumEvenIntegers([-1, 2, 3, 4, 5]) == 10
// sumEvenIntegers([]) == 0
func sumEvenIntegers(integers: [Int]) -> Int {
return integers.filter { $0 % 2 == 0 }.reduce(0, { $0 + $1 })
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes an array of integers and returns the sum of all the integers that are odd and less than 100.
// sumOddIntegersLessThan100([1, 2, 3, 4, 5]) == 9
// sumOddIntegersLessThan100([-1, 2, 3, 4, 5]) == 9
// sumOddIntegersLessThan100([]) == 0
func sumOddIntegersLessThan100(integers: [Int]) -> Int {
return integers.filter { $0 % 2 != 0 && $0 < 100 }.reduce(0, { $0 + $1 })
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes an array of integers and returns the sum of all the integers that are even and less than 100.
// sumEvenIntegersLessThan100([1, 2, 3, 4, 5]) == 10
// sumEvenIntegersLessThan100([-1, 2, 3, 4, 5]) == 10
// sumEvenIntegersLessThan100([]) == 0
func sumEvenIntegersLessThan100(integers: [Int]) -> Int {
return integers.filter { $0 % 2 == 0 && $0 < 100 }.reduce(0, { $0 + $1 })
}
// ----------------------------------------------------------------------------------------------------------------------
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.3.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func sumArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 })
}
func averageArray(array: [Int]) -> Int {
return Int(array.reduce(0, { $0 + $1 }) / array.count)
}
func largestInt(array: [Int]) -> Int? {
return array.max()
}
func smallestInt(array: [Int]) -> Int? {
return array.min()
}
func largestMinusSmallest(array: [Int]) -> Int? {
return array.max()! - array.min()
}
func sumOfEvens(array: [Int]) -> Int {
return array.filter { $0 % 2 == 0 }.reduce(0, { $0 + $1 })
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.2. Write a function that takes an array of integers and returns the sum of all the integers in the array.
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, 0, 1]) == 0
// sumArray([]) == 0
func sumArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 })
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.3. Write a function that takes an array of integers and returns the average of all the integers in the array.
// averageArray([1, 2, 3, 4, 5]) == 3
// averageArray([-1, 0, 1]) == 0
// averageArray([]) == 0
func averageArray(array: [Int]) -> Int {
return Int(array.reduce(0, { $0 + $1 }) / array.count)
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.4. Write a function that takes an array of integers and returns the largest integer in the array.
// largestInt([1, 2, 3, 4, 5]) == 5
// largestInt([-1, 0, 1]) == 1
// largestInt([]) == nil
func largestInt(array: [Int]) -> Int? {
return array.max()
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.5. Write a function that takes an array of integers and returns the smallest integer in the array.
// smallestInt([1, 2, 3, 4, 5]) == 1
// smallestInt([-1, 0, 1]) == -1
// smallestInt([]) == nil
func smallestInt(array: [Int]) -> Int? {
return array.min()
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.6. Write a function that takes an array of integers and returns the difference between the largest and smallest integers in the array.
// largestMinusSmallest([1, 2, 3, 4, 5]) == 4
// largestMinusSmallest([-1, 0, 1]) == 2
// largestMinusSmallest([]) == nil
func largestMinusSmallest(array: [Int]) -> Int? {
return array.max()! - array.min()
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.7. Write a function that takes an array of integers and returns the sum of all the even integers in the array.
// sumOfEvens([1, 2, 3, 4, 5]) == 6
// sumOfEvens([-1, 0, 1]) == 0
// sumOfEvens([]) == 0
func sumOfEvens(array: [Int]) -> Int {
return array.filter { $0 % 2 == 0 }.reduce(0, { $0 + $1 })
}
// ---------------------------------------------------------------------------------------------------------------------
// 1.1.8. Write a function that takes an array of integers and returns the sum of all the odd integers in the array.
// sumOfO
return array.max()! - array.min() // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// -----------------------------------------------------------------------------
// 1.2.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// -----------------------------------------------------------------------------
// 1.1.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.154.155.156.157.158.159.160.161.162.163.164.165.166.167.168.169.170.171.172.173.174.175.176.177.178.179.180.181.182.183.184.185.186.187.188.189.190.191.192.193.194.195.196.197.198.199.200.201.202.203.204.205.206.207.208.209.210.211.212.213.214.215.216.217.218.219.220.221.222.223.224.225.226.227.228.229.230.231.232.233.234.235.236.237.238.239.240.241.242.243.244.245.246.247.248.249.250.251.252.253.254.255.256.257.258.259.260.261.262.263.264.265.266.267.268.269.27
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// 2. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 3. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 4. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 5. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 6. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 7. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 8. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 9. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 10. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 11. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return reversed
}
// 12. Given a string, return a string with the characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
var reversed = ""
for character in string {
reversed = character + reversed
}
return
reversed = character + reversed // cannot convert value of type 'Character' to expected argument type 'String'
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// 2. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 5. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 6. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 7. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test string" yields "Ths s tst strng".
// Do not count "y" as a vowel.
// removeVowels("This is a test string") == "Ths s tst strng"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("y") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test string" yields "Ths s tst strng".
// Do not count "y" as a vowel.
// removeVowels("This is a test string") == "Ths s tst strng"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("y") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.3
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test string" yields "Ths s tst strng".
// Do not count "y" as a vowel.
// removeVowels("This is a test string") == "Ths s tst strng"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("y") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.4
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test string" yields "Ths s tst strng".
// Do not count "y" as a vowel.
// removeVowels("This is a test string") == "Ths s tst strng"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("y
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a string with all the vowels removed.
// Empty string should be returned for empty input.
// removeVowels("") == ""
// removeVowels("abcdef") == "bcdf"
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("abracadabra") == "brcrcdbr"
// removeVowels("aeiouAEIOU") == ""
// removeVowels("AEIOUaeiou") == ""
// removeVowels("AEIOUaeiouAEIOU") == ""
// removeVowels("AEIOUaeiouAEIOUaeiouAEIOU") == ""
// removeVowels("AEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaei
func rollingMax(numbers: [Int]) -> [Int] {
var rollingMax = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
rollingMax.append(max)
}
return rollingMax
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var rollingMax = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
rollingMax.append(max)
}
return rollingMax
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(max(result[i - 1], numbers[i]))
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(max(result[i - 1], numbers[i]))
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for i in numbers {
if i > max {
max = i
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for i in numbers {
if i > max {
max = i
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for i in numbers {
if i > max {
max = i
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for i in numbers {
if i > max {
max = i
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
func rollingMax(numbers: [Int]) -> [Int] {
var result = [numbers.first!]
for i in 1..<numbers.count {
result.append(max(result[i - 1], numbers[i]))
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [numbers.first!]
for i in 1..<numbers.count {
result.append(max(result[i - 1], numbers[i]))
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = Int()
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------
func makePalindrome(string: String) -> String {
let reversed = reverse(string)
let prefix = string + reversed
let suffix = reverse(string)
return prefix + suffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = reverse(string)
let prefix = string + reversed
let suffix = reverse(string)
return prefix + suffix
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------
let reversed = reverse(string) // cannot find 'reverse' in scope
let suffix = reverse(string) // cannot find 'reverse' in scope
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1)))
return string + prefix.reversed()
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1)))
return string + prefix.reversed()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.2
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.4
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.6
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.7
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.8
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.9
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.10
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.11
// ---------------------------------------------------------------------------------------------------------------
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: 1) == reversed.suffix(length: 1))) // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type '[ReversedCollection<String>.Element]' (aka 'Array<Character>')
func makePalindrome(string: String) -> String {
let reversed = string.reversed().join()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed().join()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
let reversed = string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // extraneous argument label 'length:' in call
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0)))
return string + reversed.suffix(length: prefix.count)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0)))
return string + reversed.suffix(length: prefix.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.2
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.4
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.6
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.7
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.8
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.9
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.10
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.1.11
// ------------------------------
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0))) // anonymous closure argument not contained in a closure
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0))) // anonymous closure argument not contained in a closure
let prefix = string.prefix(while: (reversed.prefix(length: $0) == reversed.prefix(length: $0))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
return string + reversed.suffix(length: prefix.count) // no exact matches in call to instance method 'suffix'
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // extraneous argument label 'length:' in call
return string + reversed.prefix(length: prefix.count) // no exact matches in call to instance method 'prefix'
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.dropFirst() != string.dropFirst()))
return string + prefix.reversed()
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.dropFirst() != string.dropFirst()))
return string + prefix.reversed()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------
let prefix = string.prefix(while: (reversed.dropFirst() != string.dropFirst())) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let prefix = string.prefix(while: (reversed.dropFirst() != string.dropFirst())) // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type 'String.SubSequence' (aka 'Substring')
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.suffix(1)))
return string + reversedPrefix.reversed()
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.suffix(1)))
return string + reversedPrefix.reversed()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.suffix(1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.suffix(1))) // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type 'String.SubSequence' (aka 'Substring')
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.prefix(1)))
return string + reversedPrefix.reversed()
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.prefix(1)))
return string + reversedPrefix.reversed()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.1
// Write a function that takes a string and returns the number of times each letter appears in the string.
// countLetters("") == {}
// countLetters("a") == {"a": 1}
// countLetters("aa") == {"a": 2}
// countLetters("ab") == {"a": 1, "b": 1}
// countLetters("abc") == {"a": 1, "b": 1, "c": 1}
// countLetters("abca") == {"a": 2, "b": 1, "c": 1}
// countLetters("abcb") == {"a": 1, "b": 2, "c": 1}
// countLetters("abcc") == {"a": 1, "b": 1, "c": 2}
// countLetters("abccc") == {"a": 1, "b": 1, "c": 3}
// countLetters("abcccc") == {"a": 1, "b": 1, "c": 4}
// countLetters("abccccc") == {"a": 1, "b": 1, "c": 5}
// countLetters("abcccccc") == {"a": 1, "b": 1, "c": 6}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// countLetters("abccccccc") == {"a": 1, "b": 1, "c": 7}
// count
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.prefix(1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let reversedPrefix = string.prefix(while: (reversed.prefix(1) == string.prefix(1))) // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type 'String.SubSequence' (aka 'Substring')
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1)))
return string + reversed.prefix(length: prefix.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.12
// Write a short program that prints each number from 1 to 100 on a new line.
// For each multiple of 3, print "Fizz" instead of the number.
// For each multiple of 5, print "Buzz" instead of the number.
// For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
for i in 1...100 {
print(i)
if i % 3 == 0 {
print("Fizz")
}
if i % 5 == 0 {
print("Buzz")
}
print()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.13
// Write a short program that prints each number from 1 to 100 on a new line.
// For each multiple of 3, print "Fizz" instead of the number.
// For each multiple of 5, print "Buzz" instead of the number.
// For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
for i in 1...100 {
print(i)
if i % 3 == 0 {
print("Fizz")
}
if i % 5 == 0 {
print("Buzz")
}
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
}
print()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.14
// Write a short program that prints each number from 1 to 100 on a new line.
// For each multiple of 3, print "Fizz" instead of the number.
// For each multiple of 5, print "Buzz" instead of the number.
// For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
for i in 1...100 {
print(i)
if i % 3 == 0 {
print("Fizz")
}
if i % 5 == 0 {
print("Buzz")
}
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
}
print()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.15
// Write a short program that prints each number from 1 to 100 on a new line.
// For each multiple of 3, print "Fizz" instead of the number.
// For each multiple of 5, print "Buzz" instead of the number.
// For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
for i in 1...100 {
print(i)
if i % 3 == 0 {
print("Fizz")
}
if i % 5 == 0 {
print("Buzz")
}
if i % 3 == 0 && i % 5 == 0 {
print("FizzBuzz")
}
print()
}
// ---------------
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // cannot convert value of type 'Bool' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // extraneous argument label 'length:' in call
let prefix = string.prefix(while: (reversed.prefix(length: 1) == string.suffix(length: 1))) // cannot convert value of type 'ReversedCollection<String>.SubSequence' (aka 'Slice<ReversedCollection<String>>') to expected argument type 'String.SubSequence' (aka 'Substring')
return string + reversed.prefix(length: prefix.count) // no exact matches in call to instance method 'prefix'
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let palindrome = string + reversed
return palindrome
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = String(string.reversed())
let palindrome = string + reversed
return palindrome
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringReverse(s: String) -> String {
return String(s.reversed())
}
func stringRemoveFirst(s: String) -> String {
return s.substring(1)
}
func stringRemoveLast(s: String) -> String {
return s.substring(0, s.count - 1)
}
func stringRemoveFirstAndLast(s: String) -> String {
return s.substring(1, s.count - 1)
}
func stringReplaceFirst(s: String) -> String {
return "$" + s.substring(1)
}
func stringReplaceLast(s: String) -> String {
return s.substring(0, s.count - 1) + "$"
}
func stringReplaceFirstAndLast(s: String) -> String {
return "$" + s.substring(1, s.count - 1) + "$"
}
func stringRemoveVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func stringRemoveVowelsAndReplaceConsonants(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += "*"
} else {
result += char
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// 2. Write a function that takes a string as input and returns the string reversed.
// stringReverse("hello") == "olleh"
func stringReverse(s: String) -> String {
return String(s.reversed())
}
// 3. Write a function that takes a string as input and returns the string with the first character removed.
// stringRemoveFirst("hello") == "ello"
func stringRemoveFirst(s: String) -> String {
return s.substring(1)
}
// 4. Write a function that takes a string as input and returns the string with the last character removed.
// stringRemoveLast("hello") == "hell"
func stringRemoveLast(s: String) -> String {
return s.substring(0, s.count - 1)
}
// 5. Write a function that takes a string as input and returns the string with the first and last characters removed.
// stringRemoveFirstAndLast("hello") == "ell"
func stringRemoveFirstAndLast(s: String) -> String {
return s.substring(1, s.count - 1)
}
// 6. Write a function that takes a string as input and returns the string with the first character replaced by "$".
// stringReplaceFirst("hello") == "$ello"
func stringReplaceFirst(s: String) -> String {
return "$" + s.substring(1)
}
// 7. Write a function that takes a string as input and returns the string with the last character replaced by "$".
// stringReplaceLast("hello") == "hell$"
func stringReplaceLast(s: String) -> String {
return s.substring(0, s.count - 1) + "$"
}
// 8. Write a function that takes a string as input and returns the string with the first and last characters replaced by "$".
// stringReplaceFirstAndLast("hello") == "$ello$"
func stringReplaceFirstAndLast(s: String) -> String {
return "$" + s.substring(1, s.count - 1) + "$"
}
// 9. Write a function that takes a string as input and returns the string with all the vowels removed.
// stringRemoveVowels("hello") == "hll"
func stringRemoveVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 10. Write a function that takes a string as input and returns the string with all the vowels removed, and all the consonants replaced by "*".
// stringRemoveVowelsAndReplaceConsonants("hello") == "h*ll*"
func stringRemoveVowelsAndReplaceConsonants(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += "*"
} else {
result += char
}
}
return result
}
// 11. Write a function that takes a string as input and returns the string with all the vowels removed, and all the consonants replaced by "*", and all the digits removed.
// stringRemoveVowelsAndReplaceConsonantsAndRemoveDigits("hello123") == "h*ll*"
func stringRemoveVowelsAndReplaceConsonantsAndRemoveDigits(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return s.substring(1) // no exact matches in call to instance method 'substring'
return s.substring(0, s.count - 1) // no exact matches in call to instance method 'substring'
return s.substring(1, s.count - 1) // no exact matches in call to instance method 'substring'
return "$" + s.substring(1) // no exact matches in call to instance method 'substring'
return s.substring(0, s.count - 1) + "$" // no exact matches in call to instance method 'substring'
return "$" + s.substring(1, s.count - 1) + "$" // no exact matches in call to instance method 'substring'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringReverse(s: String) -> String {
return String(s.reversed())
}
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// stringReverse("hello") == "olleh"
func stringReverse(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string with the first character
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes a string as input and returns the string with the first letter
// capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 19
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == "1" && b[i] == "1" {
result += "0"
} else if a[i] == "0" && b[i] == "0" {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringLengthOfLongestSubstring(s: String) -> Int {
var result = 0
var left = 0
var right = 0
var map = [Character: Int]()
while right < s.count {
if map[s[right]] != nil {
left = max(left, map[s[right]]! + 1)
}
map[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == "1" && b[i] == "1" {
result += "0"
} else if a[i] == "0" && b[i] == "0" {
result += "0"
} else {
result += "1"
}
}
return result
}
// 2. Given a string, find the length of the longest substring without repeating characters.
// stringLengthOfLongestSubstring("abcabcbb") == 3
// stringLengthOfLongestSubstring("bbbbb") == 1
// stringLengthOfLongestSubstring("pwwkew") == 3
func stringLengthOfLongestSubstring(s: String) -> Int {
var result = 0
var left = 0
var right = 0
var map = [Character: Int]()
while right < s.count {
if map[s[right]] != nil {
left = max(left, map[s[right]]! + 1)
}
map[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
// 3. Given a string, find the length of the longest substring without repeating characters.
// stringLengthOfLongestSubstring("abcabcbb") == 3
// stringLengthOfLongestSubstring("bbbbb") == 1
// stringLengthOfLongestSubstring("pwwkew") == 3
func stringLengthOfLongestSubstring(s: String) -> Int {
var result = 0
var left = 0
var right = 0
var map = [Character: Int]()
while right < s.count {
if map[s[right]] != nil {
left = max(left, map[s[right]]! + 1)
}
map[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
// 4. Given a string, find the length of the longest substring without repeating characters.
// stringLengthOfLongestSubstring("abcabcbb") == 3
// stringLengthOfLongestSubstring("bbbbb") == 1
// stringLengthOfLongestSubstring("pwwkew") == 3
func stringLengthOfLongestSubstring(s: String) -> Int {
var result = 0
var left = 0
var right = 0
var map = [Character: Int]()
while right < s.count {
if map[s[right]] != nil {
left = max(left, map[s[right]]! + 1)
}
map[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
// 5. Given a string, find the length of the longest substring without repeating characters.
// stringLengthOfLongestSubstring("abcabcbb") == 3
// stringLengthOfLongestSubstring("bbbbb") == 1
// stringLengthOfLongestSubstring("pwwkew") == 3
func stringLengthOfLongestSubstring(s: String) -> Int {
var result = 0
var left = 0
var right = 0
var map = [Character: Int]()
while right < s.count {
if map[s[right]] != nil {
left = max(left, map[s[right]]! + 1)
}
map[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
// 6. Given a string, find the length of the longest substring without repeating characters.
// stringLengthOfLongestSubstring("abcabcbb") == 3
// stringLengthOfLongestSubstring("bbbbb") == 1
// stringLengthOf
if a[i] == "1" && b[i] == "1" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == "1" && b[i] == "1" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if a[i] == "0" && b[i] == "0" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if a[i] == "0" && b[i] == "0" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if map[s[right]] != nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
left = max(left, map[s[right]]! + 1) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[s[right]] = right // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == "1" && b[i] == "1" {
result += "0"
} else if a[i] == "0" && b[i] == "0" {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringReverse(s: String) -> String {
var result = ""
for i in s.count-1..<0 {
result += s[i]
}
return result
}
func stringCapitalize(s: String) -> String {
var result = ""
result += s[0].capitalized
for i in 1..<s.count {
result += s[i].lowercased
}
return result
}
func stringLowercase(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].lowercased
}
return result
}
func stringUppercase(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].uppercased
}
return result
}
func stringTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
func stringLowercaseTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
func stringUppercaseTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
if a[i] == "1" && b[i] == "1" {
result += "0"
} else if a[i] == "0" && b[i] == "0" {
result += "0"
} else {
result += "1"
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string reversed.
// stringReverse("hello") == "olleh"
func stringReverse(s: String) -> String {
var result = ""
for i in s.count-1..<0 {
result += s[i]
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string with the first letter capitalized and the rest lowercase.
// stringCapitalize("hello") == "Hello"
func stringCapitalize(s: String) -> String {
var result = ""
result += s[0].capitalized
for i in 1..<s.count {
result += s[i].lowercased
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string with all the letters converted to lowercase.
// stringLowercase("Hello") == "hello"
func stringLowercase(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].lowercased
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string with all the letters converted to uppercase.
// stringUppercase("hello") == "HELLO"
func stringUppercase(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].uppercased
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string with all the letters converted to title case.
// stringTitle("hello") == "Hello"
func stringTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string with all the letters converted to lowercase and title case.
// stringLowercaseTitle("Hello") == "Hello"
func stringLowercaseTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string with all the letters converted to uppercase and title case.
// stringUppercaseTitle("hello") == "Hello"
func stringUppercaseTitle(s: String) -> String {
var result = ""
for i in s.count {
result += s[i].capitalized
}
return result
}
// -----------------------------------------------------------------------------
// 1
if a[i] == "1" && b[i] == "1" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == "1" && b[i] == "1" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if a[i] == "0" && b[i] == "0" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if a[i] == "0" && b[i] == "0" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += s[i] // no exact matches in call to subscript
result += s[0].capitalized // no exact matches in call to subscript
result += s[i].lowercased // function produces expected type 'String'; did you mean to call it with '()'?
for i in s.count { // for-in loop requires 'Int' to conform to 'Sequence'
for i in s.count { // for-in loop requires 'Int' to conform to 'Sequence'
for i in s.count { // for-in loop requires 'Int' to conform to 'Sequence'
for i in s.count { // for-in loop requires 'Int' to conform to 'Sequence'
for i in s.count { // for-in loop requires 'Int' to conform to 'Sequence'
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
func firstUniqChar(s: String) -> Int {
var result = 0
var count = [Int](repeating: 0, count: 26)
for i in 0..<s.count {
count[s[i].asciiValue - 97] += 1
}
for i in 0..<s.count {
if count[s[i].asciiValue - 97] == 1 {
result = i
break
}
}
return result
}
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var temp = ""
for k in i..<j {
temp += s[k]
}
if temp == String(temp.reversed()) {
if temp.count > result.count {
result = temp
}
}
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 2.
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// s = "leetcode" return 0.
// s = "loveleetcode" return 2.
func firstUniqChar(s: String) -> Int {
var result = 0
var count = [Int](repeating: 0, count: 26)
for i in 0..<s.count {
count[s[i].asciiValue - 97] += 1
}
for i in 0..<s.count {
if count[s[i].asciiValue - 97] == 1 {
result = i
break
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 3.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var temp = ""
for k in i..<j {
temp += s[k]
}
if temp == String(temp.reversed()) {
if temp.count > result.count {
result = temp
}
}
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 4.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var temp = ""
for k in i..<j {
temp += s[k]
}
if temp == String(temp.reversed()) {
if temp.count > result.count {
result = temp
}
}
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 5.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += "0" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
result += "1" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
count[s[i].asciiValue - 97] += 1 // cannot convert value of type 'UInt8?' to expected argument type 'Int'
if count[s[i].asciiValue - 97] == 1 { // cannot convert value of type 'UInt8?' to expected argument type 'Int'
temp += s[k] // no exact matches in call to subscript
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringSum(input: String) -> Int {
var result = 0
var currentNumber = ""
for char in input {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
func stringBits(input: String) -> String {
var result = ""
for i in 0..<input.count {
if i % 2 == 0 {
result += input[i]
}
}
return result
}
func stringSplosion(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
result += a[0..<i+1]
}
for i in 0..<b.count {
result += b[0..<i+1]
}
return result
}
func last2(input: String) -> Int {
var result = 0
for i in 0..<input.count - 2 {
if input[i..<i+2] == input[input.count - 2..<input.count - 1] {
result += 1
}
}
return result
}
func arrayCount9(input: [Int]) -> Int {
var result = 0
for i in input {
if i == 9 {
result += 1
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// 2. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// stringSum("abc123xyz") == 123
func stringSum(input: String) -> Int {
var result = 0
var currentNumber = ""
for char in input {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
// 3. Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
// stringBits("Hello") == "Hlo"
func stringBits(input: String) -> String {
var result = ""
for i in 0..<input.count {
if i % 2 == 0 {
result += input[i]
}
}
return result
}
// 4. Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".
// stringSplosion("Code", "Rocks") == "CCoCodCodeRocRocRocksrccodocodoc"
func stringSplosion(a: String, b: String) -> String {
var result = ""
for i in 0..<a.count {
result += a[0..<i+1]
}
for i in 0..<b.count {
result += b[0..<i+1]
}
return result
}
// 5. Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
// last2("hixxhi") == 1
func last2(input: String) -> Int {
var result = 0
for i in 0..<input.count - 2 {
if input[i..<i+2] == input[input.count - 2..<input.count - 1] {
result += 1
}
}
return result
}
// 6. Given an array of ints, return the number of 9's in the array.
// arrayCount9([1, 2, 9]) == 1
// arrayCount9([1, 9, 9]) == 2
// arrayCount9([1, 9, 9, 3, 9]) == 3
func arrayCount9(input: [Int]) -> Int {
var result = 0
for i in input {
if i == 9 {
result += 1
}
}
return result
}
// 7. Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.
// arrayFront9([1, 2, 9, 3, 4]) == true
// arrayFront9([1, 2, 3, 4, 9]) == false
// arrayFront9([1, 2, 3, 4, 5]) == false
func arrayFront9(input: [Int]) -> Bool {
for i in 0..<input.count {
if input[i] == 9 {
return true
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += "0" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
result += "1" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
if char.isDigit { // value of type 'Character' has no member 'isDigit'
currentNumber += char // cannot convert value of type 'Character' to expected argument type 'String'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += input[i] // no exact matches in call to subscript
result += a[0..<i+1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
result += b[0..<i+1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if input[i..<i+2] == input[input.count - 2..<input.count - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if input[i..<i+2] == input[input.count - 2..<input.count - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
func stringReverse(s: String) -> String {
return String(s.reversed())
}
func stringCapitalize(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] == " " {
result += " "
} else {
result += String(s[i].uppercased())
}
}
return result
}
func stringRemoveVowels(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" {
result += s[i]
}
}
return result
}
func stringRemoveSpaces(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != " " {
result += s[i]
}
}
return result
}
func stringReverseLetters(s: String) -> String {
var result = ""
for i in 0..<s.count {
result = s[i] + result
}
return result
}
func stringAlphabetPosition(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] == " " {
result += " "
} else {
result += String(s[i].asciiValue - 96)
}
}
return result
}
func stringRemoveLetters(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" {
result += s[i]
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let result = ""
for i in 0..<a.count {
if a[i] == b[i] {
result += "0"
} else {
result += "1"
}
}
return result
}
// 2. Write a function that takes a string as input and returns the string reversed.
// stringReverse("hello") == "olleh"
func stringReverse(s: String) -> String {
return String(s.reversed())
}
// 3. Write a function that takes a string as input and returns the string with the first character of each word capitalized.
// stringCapitalize("hello world") == "Hello World"
func stringCapitalize(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] == " " {
result += " "
} else {
result += String(s[i].uppercased())
}
}
return result
}
// 4. Write a function that takes a string as input and returns the string with all the vowels removed.
// stringRemoveVowels("hello world") == "hll wrld"
func stringRemoveVowels(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" {
result += s[i]
}
}
return result
}
// 5. Write a function that takes a string as input and returns the string with all the spaces removed.
// stringRemoveSpaces("hello world") == "helloworld"
func stringRemoveSpaces(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != " " {
result += s[i]
}
}
return result
}
// 6. Write a function that takes a string as input and returns the string with all the letters reversed.
// stringReverseLetters("hello world") == "dlrow olleh"
func stringReverseLetters(s: String) -> String {
var result = ""
for i in 0..<s.count {
result = s[i] + result
}
return result
}
// 7. Write a function that takes a string as input and returns the string with all the letters replaced by their positions in the alphabet.
// stringAlphabetPosition("hello world") == "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12"
func stringAlphabetPosition(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] == " " {
result += " "
} else {
result += String(s[i].asciiValue - 96)
}
}
return result
}
// 8. Write a function that takes a string as input and returns the string with all the letters removed.
// stringRemoveLetters("hello world") == "hll wrld"
func stringRemoveLetters(s: String) -> String {
var result = ""
for i in 0..<s.count {
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" {
result += s[i]
}
}
return result
}
// 9. Write a function that takes a string as input and returns the string with all the letters replaced by their positions in the alphabet.
// stringAlphabetPositionLetters("hello
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += "0" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
result += "1" // left side of mutating operator isn't mutable: 'result' is a 'let' constant
if s[i] == " " { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += String(s[i].uppercased()) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += s[i] // no exact matches in call to subscript
if s[i] != " " { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += s[i] // no exact matches in call to subscript
result = s[i] + result // no exact matches in call to subscript
if s[i] == " " { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += String(s[i].asciiValue - 96) // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != "a" && s[i] != "e" && s[i] != "i" && s[i] != "o" && s[i] != "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += s[i] // no exact matches in call to subscript
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
//
if string.length > longest.length { // value of type 'String' has no member 'length'
if string.length > longest.length { // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (longest, next) in
if longest.length < next.length {
return next
} else {
return longest
}
})
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (longest, next) in
if longest.length < next.length {
return next
} else {
return longest
}
})
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// ------------------------------
if longest.length < next.length { // value of type 'String' has no member 'length'
if longest.length < next.length { // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (longest, string) in
return longest.length > string.length ? longest : string
})
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (longest, string) in
return longest.length > string.length ? longest : string
})
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------
return longest.length > string.length ? longest : string // value of type 'String' has no member 'length'
return longest.length > string.length ? longest : string // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
func min(numbers: [Int]) -> Int {
var min = numbers[0]
for number in numbers {
if number < min {
min = number
}
}
return min
}
func max(numbers: [Int]) -> Int {
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
}
return max
}
func range(numbers: [Int]) -> Int {
return max(numbers: numbers) - min(numbers: numbers)
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
// ------------------------------------------------------------------------------------------------
// 2. Write a function that takes an array of numbers and returns the sum of all the numbers.
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// ------------------------------------------------------------------------------------------------
// 3. Write a function that takes an array of numbers and returns the average of all the numbers.
// average([1, 2, 3]) == 2
// average([1, 2, 3, 4]) == 2.5
// average([1, 2, 3, 4, 5]) == 3
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
// ------------------------------------------------------------------------------------------------
// 4. Write a function that takes an array of numbers and returns the minimum number.
// min([1, 2, 3]) == 1
// min([1, 2, 3, 4]) == 1
// min([1, 2, 3, 4, 5]) == 1
func min(numbers: [Int]) -> Int {
var min = numbers[0]
for number in numbers {
if number < min {
min = number
}
}
return min
}
// ------------------------------------------------------------------------------------------------
// 5. Write a function that takes an array of numbers and returns the maximum number.
// max([1, 2, 3]) == 3
// max([1, 2, 3, 4]) == 4
// max([1, 2, 3, 4, 5]) == 5
func max(numbers: [Int]) -> Int {
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
}
return max
}
// ------------------------------------------------------------------------------------------------
// 6. Write a function that takes an array of numbers and returns the range of the numbers.
// range([1, 2, 3]) == 2
// range([1, 2, 3, 4]) == 3
// range([1, 2, 3, 4, 5]) == 4
func range(numbers: [Int]) -> Int {
return max(numbers: numbers) - min(numbers: numbers)
}
// ------------------------------------------------------------------------------------------------
// 7. Write a function that takes an array of numbers and returns the median number.
// median([1, 2, 3]) == 2
// median([1, 2, 3, 4]) == 2.5
// median([1, 2, 3, 4, 5]) == 3
func median(numbers: [Int]) -> Int {
var sortedNumbers = numbers
sortedNumbers.sort()
var middle = sortedNumbers.count / 2
if sortedNumbers.count % 2 == 0 {
return (sortedNumbers[middle - 1] + sortedNumbers[middle]) / 2
if string.length > longest.length { // value of type 'String' has no member 'length'
if string.length > longest.length { // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (l, r) -> String in
return l.length > r.length ? l : r
})
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
return strings.reduce(strings[0], { (l, r) -> String in
return l.length > r.length ? l : r
})
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------
return l.length > r.length ? l : r // value of type 'String' has no member 'length'
return l.length > r.length ? l : r // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var maxLength = 0
var maxLengthString: String? = nil
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxLengthString = string
}
}
return maxLengthString
}
func sum(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + integer })
}
func sumOfEvens(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) })
}
func sumOfOdds(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) })
}
func sumOfGreaterThanFive(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) })
}
func sumOfLessThanFive(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var maxLength = 0
var maxLengthString: String? = nil
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxLengthString = string
}
}
return maxLengthString
}
// ------------------------------------------------------------------------------------------------
// 1.1.2
// Given an array of integers, return the sum of all the integers.
// sum(integers: []) == 0
// sum(integers: [1, 2, 3]) == 6
func sum(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + integer })
}
// ------------------------------------------------------------------------------------------------
// 1.1.3
// Given an array of integers, return the sum of all the even integers.
// sumOfEvens(integers: []) == 0
// sumOfEvens(integers: [1, 2, 3]) == 2
// sumOfEvens(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 30
func sumOfEvens(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) })
}
// ------------------------------------------------------------------------------------------------
// 1.1.4
// Given an array of integers, return the sum of all the odd integers.
// sumOfOdds(integers: []) == 0
// sumOfOdds(integers: [1, 2, 3]) == 4
// sumOfOdds(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 25
func sumOfOdds(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) })
}
// ------------------------------------------------------------------------------------------------
// 1.1.5
// Given an array of integers, return the sum of all the integers that are greater than 5.
// sumOfGreaterThanFive(integers: []) == 0
// sumOfGreaterThanFive(integers: [1, 2, 3]) == 0
// sumOfGreaterThanFive(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 30
func sumOfGreaterThanFive(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) })
}
// ------------------------------------------------------------------------------------------------
// 1.1.6
// Given an array of integers, return the sum of all the integers that are less than 5.
// sumOfLessThanFive(integers: []) == 0
// sumOfLessThanFive(integers: [1, 2, 3]) == 0
// sumOfLessThanFive(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 15
func sumOfLessThanFive(integers: [Int]) -> Int {
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) })
}
// ---------------
return integers.reduce(0, \(sum, integer) { sum + integer }) // expected ',' separator
return integers.reduce(0, \(sum, integer) { sum + integer }) // extra argument in call
return integers.reduce(0, \(sum, integer) { sum + integer }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + integer }) // string interpolation can only appear inside a string literal
return integers.reduce(0, \(sum, integer) { sum + integer }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + integer }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // extra argument in call
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // string interpolation can only appear inside a string literal
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // cannot convert value of type '([Int]) -> Int' to expected argument type 'Int'
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 == 0 ? integer : 0) }) // expected ',' separator
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // expected ',' separator
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // cannot convert value of type '([Int]) -> Int' to expected argument type 'Int'
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // string interpolation can only appear inside a string literal
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // extra argument in call
return integers.reduce(0, \(sum, integer) { sum + (integer % 2 != 0 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // string interpolation can only appear inside a string literal
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // expected ',' separator
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // cannot convert value of type '([Int]) -> Int' to expected argument type 'Int'
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // extra argument in call
return integers.reduce(0, \(sum, integer) { sum + (integer > 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // extra argument in call
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // string interpolation can only appear inside a string literal
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // expected ',' separator
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // cannot find 'integer' in scope
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return integers.reduce(0, \(sum, integer) { sum + (integer < 5 ? integer : 0) }) // cannot convert value of type '([Int]) -> Int' to expected argument type 'Int'
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func firstUniqChar(s: String) -> Int {
var dict = [String: Int]()
for i in 0..<s.length {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
}
for i in 0..<s.length {
if dict[s[i]] == 1 {
return i
}
}
return -1
}
func countElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j && nums[i] > nums[j] && nums[i] < nums[j] {
count += 1
}
}
}
return count
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.count == 0 {
return nil
}
var longest = strings[0]
for string in strings {
if string.length > longest.length {
longest = string
}
}
return longest
}
// ------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// ------------------------------------------------------------------------------------------------
// 2. Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
// firstUniqChar("") == -1
func firstUniqChar(s: String) -> Int {
var dict = [String: Int]()
for i in 0..<s.length {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
}
for i in 0..<s.length {
if dict[s[i]] == 1 {
return i
}
}
return -1
}
// ------------------------------------------------------------------------------------------------
// 3. Given an integer array nums, return the number of elements that have both a strictly smaller
// and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
// countElements(nums: [-3,3,3,90]) == 2
// countElements(nums: [29,6,10]) == 2
func countElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j && nums[i] > nums[j] && nums[i] < nums[j] {
count += 1
}
}
}
return count
}
// ------------------------------------------------------------------------------------------------
// 4. Given an integer array nums, return the number of elements that have both a strictly
// smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
// countElements(nums: [-3,3,3,90]) == 2
// countElements(nums: [29,6,10]) == 2
func countElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j && nums[i] > nums[j] && nums[i] < nums[j] {
count += 1
}
}
}
return count
}
// ------------------------------------------------------------------------------------------------
// 5. Given an integer array nums, return the number of elements that have both a strictly
// smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
// countElements(nums: [-3,3
if string.length > longest.length { // value of type 'String' has no member 'length'
if string.length > longest.length { // value of type 'String' has no member 'length'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
for i in 0..<s.length { // value of type 'String' has no member 'length'
for i in 0..<s.length { // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
return strings.max(by: { $0.length })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
return strings.max(by: { $0.length })
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return strings.max(by: { $0.length }) // contextual closure type '(String, String) throws -> Bool' expects 2 arguments, but 1 was used in closure body
return strings.max(by: { $0.length }) // value of type 'String' has no member 'length'
func longest(strings: [String]) -> String? {
return strings.max { $0.length < $1.length }
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, \(sum, number) { sum + number })
}
func sumOdd(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number })
}
func sumEven(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number })
}
func sumOddGreaterThan5(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number })
}
func sumEvenGreaterThan5(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number })
}
func sumEvenLessThan10(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
return strings.max { $0.length < $1.length }
}
// ------------------------------------------------------------------------------------------------
// 1.1.2
// Given an array of integers, return the sum of all the integers.
// sum(numbers: []) == 0
// sum(numbers: [1, 2, 3]) == 6
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, \(sum, number) { sum + number })
}
// ------------------------------------------------------------------------------------------------
// 1.1.3
// Given an array of integers, return the sum of all the integers that are odd.
// sumOdd(numbers: []) == 0
// sumOdd(numbers: [1, 2, 3]) == 4
func sumOdd(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number })
}
// ------------------------------------------------------------------------------------------------
// 1.1.4
// Given an array of integers, return the sum of all the integers that are even.
// sumEven(numbers: []) == 0
// sumEven(numbers: [1, 2, 3]) == 4
func sumEven(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number })
}
// ------------------------------------------------------------------------------------------------
// 1.1.5
// Given an array of integers, return the sum of all the integers that are odd and greater than 5.
// sumOddGreaterThan5(numbers: []) == 0
// sumOddGreaterThan5(numbers: [1, 2, 3]) == 0
// sumOddGreaterThan5(numbers: [6, 7, 8]) == 12
func sumOddGreaterThan5(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number })
}
// ------------------------------------------------------------------------------------------------
// 1.1.6
// Given an array of integers, return the sum of all the integers that are even and greater than 5.
// sumEvenGreaterThan5(numbers: []) == 0
// sumEvenGreaterThan5(numbers: [1, 2, 3]) == 0
// sumEvenGreaterThan5(numbers: [6, 7, 8]) == 12
func sumEvenGreaterThan5(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number })
}
// ------------------------------------------------------------------------------------------------
// 1.1.7
// Given an array of integers, return the sum of all the integers that are even and less than 10.
// sumEvenLessThan10(numbers: []) == 0
// sumEvenLessThan10(numbers: [1, 2, 3]) == 2
// sumEvenLessThan10(numbers: [6, 7, 8]) == 12
func sumEvenLessThan10(numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number })
}
// ---------------------------------
return strings.max { $0.length < $1.length } // value of type 'String' has no member 'length'
return strings.max { $0.length < $1.length } // value of type 'String' has no member 'length'
return numbers.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.reduce(0, \(sum, number) { sum + number }) // extra argument in call
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // extra argument in call
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.filter { $0 % 2 == 1 }.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // extra argument in call
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 }.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // extra argument in call
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.filter { $0 % 2 == 1 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // extra argument in call
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 && $0 > 5 }.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // expected ',' separator
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // string interpolation can only appear inside a string literal
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // cannot find 'number' in scope
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return numbers.filter { $0 % 2 == 0 && $0 < 10 }.reduce(0, \(sum, number) { sum + number }) // extra argument in call
func longest(strings: [String]) -> String? {
return strings.first(where: { $0.count > 0 })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
return strings.first(where: { $0.count > 0 })
}
// -------------------------------------------------------------------------------------------------
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Note: This is a slightly different version of the "fix string" exercise from the strings section.
// fixString("Example") == "eXAMPLe"
// fixString("Example string") == "eXAMPLe STRING"
// fixString("Example string!") == "eXAMPLe STRING!"
// fixString("Example string!@") == "eXAMPLe STRING!@"
// fixString("") == ""
// -------------------------------------------------------------------------------------------------
// Given a string, return the boolean true if the string is a palindrome.
// A palindrome is a word or sentence that's spelled the same forwards and backwards.
// Note: You should ignore punctuation, spaces, and capitalization.
// isPalindrome("a") == true
// isPalindrome("ab") == false
// isPalindrome("aba") == true
// isPalindrome("abba") == true
// isPalindrome("abab") == false
// isPalindrome("amanaplanacanalpanama") == true
// isPalindrome("amanaplanacanalpandemonium") == false
// -------------------------------------------------------------------------------------------------
// Given a string, return the boolean true if the string is a palindrome.
// A palindrome is a word or sentence that's spelled the same forwards and backwards.
// Note: You should ignore punctuation, spaces, and capitalization.
// isPalindrome("a") == true
// isPalindrome("ab") == false
// isPalindrome("aba") == true
// isPalindrome("abba") == true
// isPalindrome("abab") == false
// isPalindrome("amanaplanacanalpanama") == true
// isPalindrome("amanaplanacanalpandemonium") == false
// -------------------------------------------------------------------------------------------------
// Given a string, return the boolean true if the string is a palindrome.
// A palindrome is a word or sentence that's spelled the same forwards and backwards.
// Note: You should ignore punctuation, spaces, and capitalization.
// isPalindrome("a") == true
// isPalindrome("ab") == false
// isPalindrome("aba") == true
// isPalindrome("abba") == true
// isPalindrome("abab") == false
// isPalindrome("amanaplanacanalpanama") == true
// isPalindrome("amanaplanacanalpandemonium") == false
// -------------------------------------------------------------------------------------------------
// Given a string, return the boolean true if the string is a palindrome.
// A palindrome is a word or sentence that's spelled the same forwards and backwards.
// Note: You should ignore punctuation, spaces, and capitalization.
// isPalindrome("a") == true
// isPalindrome("ab") == false
// isPalindrome("aba") == true
// isPalindrome("abba") == true
// isPalindrome(
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
while b != 0 {
let temp = b
b = a % b
a = temp
}
return a
}
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// M
b = a % b // cannot assign to value: 'b' is a 'let' constant
a = temp // cannot assign to value: 'a' is a 'let' constant
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
func reverseString(string: String) -> String {
var reversedString = ""
for i in string.reversed() {
reversedString += String(i)
}
return reversedString
}
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
var reversedString = ""
for i in string.reversed() {
reversedString += String(i)
}
return reversedString
}
// 3. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 4. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 5. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 6. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 7. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 8. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 9. Write a function that takes an integer and returns the number of 1 bits it has.
// hammingWeight(0b00000000000000000000000000001011) == 3
func hammingWeight(n: Int) -> Int {
var count =
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a % b, b: b)
}
return greatestCommonDivisor(a: a, b: b % a)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a % b, b: b)
}
return greatestCommonDivisor(a: a, b: b % a)
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as a parameter and returns a new string that
// contains all the characters in the original string except the first and last
// characters. The length of the returned string should be 1 less than the original
// string's length. If the original string has fewer than 2 characters, the returned
// string should be empty.
//
// Example:
//
// removeFirstLast("Hello") == "ell"
// removeFirstLast("abcdefg") == "bcdef"
// removeFirstLast("ab") == ""
// removeFirstLast("a") == ""
// removeFirstLast("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as a parameter and returns a new string that
// contains all the characters in the original string except the first and last
// characters. The length of the returned string should be 1 less than the original
// string's length. If the original string has fewer than 2 characters, the returned
// string should be empty.
//
// Example:
//
// removeFirstLast("Hello") == "ell"
// removeFirstLast("abcdefg") == "bcdef"
// removeFirstLast("ab") == ""
// removeFirstLast("a") == ""
// removeFirstLast("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as a parameter and returns a new string that
// contains all the characters in the original string except the first and last
// characters. The length of the returned string should be 1 less than the original
// string's length. If the original string has fewer than 2 characters, the returned
// string should be empty.
//
// Example:
//
// removeFirstLast("Hello") == "ell"
// removeFirstLast("abcdefg") == "bcdef"
// removeFirstLast("ab") == ""
// removeFirstLast("a") == ""
// removeFirstLast("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as a parameter and returns a new string that
// contains all the characters in the original string except the first and last
// characters. The length of the returned string should be 1 less than the original
// string's length. If the original string has fewer than 2 characters, the returned
// string should be empty.
//
// Example:
//
// removeFirstLast("Hello") == "ell"
// removeFirstLast("abcdefg") == "bcdef"
// removeFirstLast("ab") == ""
// removeFirstLast("a") == ""
// removeFirstLast("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
// -----------------------------------------------------------------------------
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// MARK: -
// M
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.10
// -----------------------------------------------------------------------------
// Return the greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.11
// -----------------------------------------------------------------------------
// Return the greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.12
// -----------------------------------------------------------------------------
// Return the greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.13
// -----------------------------------------------------------------------------
// Return the greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a % i == 0 && b % i == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.14
// -----------------------------------------------------------------------------
// Return the greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var result = 1
for i in 1...min(a, b) {
if a %
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------
func greatestCommonDivisor(a: Int, b: Int) -> Int {
let min = min(a, b)
for i in (1...min) {
if a % i == 0 && b % i == 0 {
return i
}
}
return 1
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
let min = min(a, b)
for i in (1...min) {
if a % i == 0 && b % i == 0 {
return i
}
}
return 1
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------------
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = a
var b = b
while a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: -
// ------------------------------------------------------------
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
prefixes.append(string[0..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
prefixes.append(string[0..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
prefixes.append(string[..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func allPrefixes(string: String) -> [String] {
var prefixes = [String()]
for character in string {
prefixes.append(prefixes.last! + character)
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String()]
for character in string {
prefixes.append(prefixes.last! + character)
}
return prefixes
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
prefixes.append(prefixes.last! + character) // cannot convert value of type 'Character' to expected argument type 'String'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
// -----------------------------------------------------------------------------
// 1.2.2.3.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
prefixes.append(string[0..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1..<string.count {
prefixes.append(string[..<i])
}
return prefixes
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
func isPalindrome(string: String) -> Bool {
var reversed = ""
for char in string {
reversed = char + reversed
}
return string == reversed
}
func letterCounts(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
return counts
}
func letterCountsNoWhitespace(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if char.isLetter {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
}
return counts
}
func letterCountsNoWhitespaceOrPunctuation(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if char.isLetter || char.isNumber {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
}
return counts
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1..<string.count {
prefixes.append(string[..<i])
}
return prefixes
}
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels(string: "abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
func isPalindrome(string: String) -> Bool {
var reversed = ""
for char in string {
reversed = char + reversed
}
return string == reversed
}
// 4. Write a function that takes a string and returns the number of times each letter appears in the string.
// letterCounts(string: "hello") == ["h": 1, "e": 1, "l": 2, "o": 1]
func letterCounts(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
return counts
}
// 5. Write a function that takes a string and returns the number of times each letter appears in the string, excluding whitespace.
// letterCountsNoWhitespace(string: "hello world") == ["h": 1, "e": 1, "l": 2, "o": 1, "w": 1, "r": 1, "d": 1]
func letterCountsNoWhitespace(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if char.isLetter {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
}
return counts
}
// 6. Write a function that takes a string and returns the number of times each letter appears in the string, excluding whitespace and punctuation.
// letterCountsNoWhitespaceOrPunctuation(string: "hello world!") == ["h": 1, "e": 1, "l": 2, "o": 1, "w": 1, "r": 1, "d": 1]
func letterCountsNoWhitespaceOrPunctuation(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if char.isLetter || char.isNumber {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
}
return counts
}
// 7. Write a function that takes a string and returns the number of times each letter appears in the string, excluding whitespace, punctuation, and numbers.
// letterCountsNoWhitespaceOrPunctuationOrNumbers(string: "hello world!") == ["h": 1, "e": 1, "l": 2, "o": 1, "w": 1, "r": 1, "d": 1]
func letterCountsNoWhitespaceOrPunctuationOrNumbers(string: String) -> [String: Int] {
var counts = [String: Int]()
for char in string {
if char.isLetter || char.isNumber {
if let count = counts[char] {
counts[char] = count + 1
} else {
counts[char] = 1
}
}
prefixes.append(string[..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
if let count = counts[char] { // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = count + 1 // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = 1 // cannot convert value of type 'Character' to expected argument type 'String'
if let count = counts[char] { // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = count + 1 // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = 1 // cannot convert value of type 'Character' to expected argument type 'String'
if let count = counts[char] { // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = count + 1 // cannot convert value of type 'Character' to expected argument type 'String'
counts[char] = 1 // cannot convert value of type 'Character' to expected argument type 'String'
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if isVowel(char: char) {
count += 1
}
}
return count
}
func isPalindrome(string: String) -> Bool {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed == string
}
func countCharacters(string: String, character: Character) -> Int {
var count = 0
for char in string {
if char == character {
count += 1
}
}
return count
}
func countCharacters(string: String) -> [Character: Int] {
var result = [Character: Int]()
for char in string {
if result[char] == nil {
result[char] = 1
} else {
result[char] += 1
}
}
return result
}
func countCharacters(string: String) -> [Character: Int] {
var result = [Character: Int]()
for char in string {
if char != " " {
if result[char] == nil {
result[char] = 1
} else {
result[char] += 1
}
}
}
return result
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
// 2. Write a function that takes a string and returns the string with all vowels removed.
// removeVowels(string: "abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns the number of vowels in the string.
// countVowels(string: "abcdefghijklmnopqrstuvwxyz") == 5
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if isVowel(char: char) {
count += 1
}
}
return count
}
// 4. Write a function that takes a string and returns true if the string is a palindrome, false otherwise.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
func isPalindrome(string: String) -> Bool {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed == string
}
// 5. Write a function that takes a string and returns the number of times a specific character appears in the string.
// countCharacters(string: "apple", character: "p") == 2
// countCharacters(string: "banana", character: "n") == 3
func countCharacters(string: String, character: Character) -> Int {
var count = 0
for char in string {
if char == character {
count += 1
}
}
return count
}
// 6. Write a function that takes a string and returns the number of times each character appears in the string.
// countCharacters(string: "apple") == ["a": 1, "p": 2, "l": 1, "e": 1]
// countCharacters(string: "banana") == ["b": 1, "a": 3, "n": 2]
func countCharacters(string: String) -> [Character: Int] {
var result = [Character: Int]()
for char in string {
if result[char] == nil {
result[char] = 1
} else {
result[char] += 1
}
}
return result
}
// 7. Write a function that takes a string and returns the number of times each character appears in the string, excluding whitespace.
// countCharacters(string: "apple") == ["a": 1, "p": 2, "l": 1, "e": 1]
// countCharacters(string: "banana") == ["b": 1, "a": 3, "n": 2]
// countCharacters(string: " apple ") == ["a": 1, "p": 2, "l": 1, "e": 1]
func countCharacters(string: String) -> [Character: Int] {
var result = [Character: Int]()
for char in string {
if char != " " {
if result[char] == nil {
result[char] = 1
} else {
result[char] += 1
}
}
}
return result
}
// 8. Write a function that takes a string and returns the number of times each character appears in the string, excluding whitespace and punctuation.
// countCharacters(string: "apple") == ["a": 1, "p": 2, "l": 1, "e": 1]
// countCharacters(string: "banana") == ["b": 1, "a": 3, "n":
prefixes.append(string[..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if !isVowel(char: char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if isVowel(char: char) { // cannot find 'isVowel' in scope
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
result[char] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func countCharacters(string: String) -> [Character: Int] { // invalid redeclaration of 'countCharacters(string:)'
result[char] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func allPrefixes(string: String) -> [String] {
var prefixes = [String()]
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
func vowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func palindrome(string: String) -> Bool {
var reversed = String(string.reversed())
return string == reversed
}
func countChar(string: String, char: String) -> Int {
var count = 0
for char in string {
if char == char {
count += 1
}
}
return count
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String()]
for i in 0..<string.count {
prefixes.append(string[0..<i])
}
return prefixes
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// vowels("aeiou") == 5
// vowels("bcdfghjklmnpqrstvwxyz") == 0
// vowels("") == 0
// vowels("aeiouAEIOU") == 10
func vowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 3. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// palindrome("abba") == true
// palindrome("abc") == false
// palindrome("") == true
// palindrome("abcdcba") == true
// palindrome("abcdefgfedcba") == true
// palindrome("abcdefgfedcbaa") == false
func palindrome(string: String) -> Bool {
var reversed = String(string.reversed())
return string == reversed
}
// 4. Write a function that takes a string and returns the number of times a specific character appears in the string.
// countChar("apple", "p") == 2
// countChar("apple", "z") == 0
// countChar("", "z") == 0
// countChar("apple", "") == 0
// countChar("apple", "a") == 2
// countChar("apple", "e") == 1
// countChar("apple", "l") == 2
// countChar("apple", "p") == 2
// countChar("apple", "z") == 0
func countChar(string: String, char: String) -> Int {
var count = 0
for char in string {
if char == char {
count += 1
}
}
return count
}
// 5. Write a function that takes a string and returns the number of times each character appears in the string.
// countChars("apple") == ["a": 1, "p": 2, "l": 1, "e": 1]
// countChars("") == ["a": 0, "p": 0, "l": 0, "e": 0]
// countChars("appleapple") == ["a": 2, "p": 2, "l": 1, "e": 2]
// countChars("applepearple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapplepearple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapplepearpleapple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapplepearpleapplepearple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapplepearpleapplepearpleapple") == ["a": 2, "p": 3, "l": 1, "e": 2]
// countChars("applepearpleapplepearpleapplepearpleapplepearple") == ["a": 2, "p": 3, "l":
prefixes.append(string[0..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
var reversed = String(string.reversed()) // variable 'reversed' was never mutated; consider changing to 'let' constant
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1..<string.count {
prefixes.append(string[..<i])
}
return prefixes
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countAs(string: String) -> Int {
return string.count(character: "a")
}
func countAsExcludingVowels(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
func countAsExcludingVowelsAndConsonants(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
if isConsonant(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
func countAsExcludingVowelsAndConsonantsAndX(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
if isConsonant(string: string[i..<i+1]) {
continue
}
if isX(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1..<string.count {
prefixes.append(string[..<i])
}
return prefixes
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the string with all
// characters reversed.
//
// reverseString(string: "abc") == "cba"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of times
// the letter "a" appears in it.
//
// countAs(string: "apple") == 2
func countAs(string: String) -> Int {
return string.count(character: "a")
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, excluding the ones immediately after vowels.
//
// countAsExcludingVowels(string: "apple") == 1
func countAsExcludingVowels(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, excluding the ones immediately after vowels,
// and excluding the ones immediately before consonants.
//
// countAsExcludingVowelsAndConsonants(string: "apple") == 0
func countAsExcludingVowelsAndConsonants(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
if isConsonant(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, excluding the ones immediately after vowels,
// and excluding the ones immediately before consonants, and excluding the
// ones that are preceded by "x".
//
// countAsExcludingVowelsAndConsonantsAndX(string: "apple") == 1
func countAsExcludingVowelsAndConsonantsAndX(string: String) -> Int {
var count = 0
for i in 0..<string.count {
if string[i] == "a" {
if isVowel(string: string[i..<i+1]) {
continue
}
if isConsonant(string: string[i..<i+1]) {
continue
}
if isX(string: string[i..<i+1]) {
continue
}
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, excluding the ones immediately after vowels,
// and excluding the ones immediately before conson
prefixes.append(string[..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string.count(character: "a") // cannot call value of non-function type 'Int'
if string[i] == "a" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if isVowel(string: string[i..<i+1]) { // cannot find 'isVowel' in scope
if string[i] == "a" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if isVowel(string: string[i..<i+1]) { // cannot find 'isVowel' in scope
if isConsonant(string: string[i..<i+1]) { // cannot find 'isConsonant' in scope
if string[i] == "a" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if isVowel(string: string[i..<i+1]) { // cannot find 'isVowel' in scope
if isConsonant(string: string[i..<i+1]) { // cannot find 'isConsonant' in scope
if isX(string: string[i..<i+1]) { // cannot find 'isX' in scope
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func isPalindrome(string: String) -> Bool {
return string == string.reversed()
}
func countA(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
func swapFirstLast(string: String) -> String {
if string.count == 0 {
return ""
}
return string.last + string[1..<string.count - 1] + string[0]
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [string]
for i in 1...string.count {
prefixes.append(string[..<i])
}
return prefixes
}
// 2. Write a function that takes a string and returns the number (count) of vowels contained within it.
// vowelCount(string: "aeiou") == 5
// vowelCount(string: "abcdefg") == 0
// vowelCount(string: "") == 0
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 3. Write a function that takes a string and returns true if the string is a palindrome, and false if it is not.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
// isPalindrome(string: "") == true
func isPalindrome(string: String) -> Bool {
return string == string.reversed()
}
// 4. Write a function that takes a string and returns the number (count) of times the character "a" appears in it.
// countA(string: "apple") == 1
// countA(string: "banana") == 2
// countA(string: "") == 0
func countA(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
// 5. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapFirstLast(string: "apple") == "eplla"
// swapFirstLast(string: "banana") == "anaban"
// swapFirstLast(string: "") == ""
func swapFirstLast(string: String) -> String {
if string.count == 0 {
return ""
}
return string.last + string[1..<string.count - 1] + string[0]
}
// 6. Write a function that takes a string and returns true if the string is a palindrome, and false if it is not.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
// isPalindrome(string: "") == true
func isPalindrome(string: String) -> Bool {
return string == string.reversed()
}
// 7. Write a function that takes a string and returns the number (count) of times the character "a" appears in it.
// countA(string: "apple") == 1
// countA(string: "banana") == 2
// countA(string: "") == 0
func countA(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
// 8. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapFirstLast(string: "apple") == "eplla"
// swapFirstLast(string: "banana") == "anaban"
// swapFirstLast(string: "") == ""
func swapFirstLast(string: String) -> String {
if string.count == 0 {
return ""
}
return string.last + string[1..<string.count - 1] + string[0]
}
// 9. Write a function that takes a string and returns true if the string is a palindrome, and false if it is not.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
// isPalindrome(string: "") == true
func isPalindrome(string: String) -> Bool {
prefixes.append(string[..<i]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return string == string.reversed() // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
return string.last + string[1..<string.count - 1] + string[0] // cannot convert value of type 'Character' to expected argument type 'String'
return string.last + string[1..<string.count - 1] + string[0] // cannot convert value of type 'String.Element?' (aka 'Optional<Character>') to expected argument type 'String'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
// removeVowels("a") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
// removeVowels("bcdfghjklmnpqrstvwxz") == "bcdfghjklmnpqrstvwxz"
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz") == "bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz"
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghjklmnpqrstvwxz")
// removeVowels("bcdfghjklmnpqrstvwxzBcdfghj
return result.trim() // value of type 'String' has no member 'trim'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// The 32-bit integer 11 has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes an integer and returns the number of times the number 1 appears in all its decimal representation.
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes an integer and returns the number of times the number 1 appears in all its decimal representation.
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes an integer and returns the number of times the number 1 appears in all its decimal representation.
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
// ---------------------------------------------------------------------------------------
return result.trim() // value of type 'String' has no member 'trim'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trimEnd()
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trimEnd()
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return result.trimEnd() // value of type 'String' has no member 'trimEnd'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trim()
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
return result.trim() // value of type 'String' has no member 'trim'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trim()
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
//
return result.trim() // value of type 'String' has no member 'trim'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == " hll wrd"
// removeVowels("cucumber") == " cmbtr"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == " hll wrd"
// removeVowels("cucumber") == " cmbtr"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == " hll wrd"
// removeVowels("cucumber") == " cmbtr"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trimmingTrailingWhitespace()
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result.trimmingTrailingWhitespace()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
return result.trimmingTrailingWhitespace() // value of type 'String' has no member 'trimmingTrailingWhitespace'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "HHeelllloo"
// stringDoubler("Goodbye") == "GGoooodddbbYYbyyeeezzz"
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "HHeelllloo"
// stringDoubler("Goodbye") == "GGoooodddbbYYbyyeeezzz"
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "HHeelllloo"
// stringDoubler("Goodbye") == "GGoooodddbbYYbyyeeezzz"
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "HHeelllloo"
// stringDoubler("Goodbye") == "GGoooodddbbYYbyyeeezzz"
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "HHeelllloo"
// stringDoubler("Goodbye") == "GGoooodddbbYYbyyeeezzz"
func stringDoubler(s: String) -> String {
var result = ""
for char in s {
result += String(char) + String(char)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each letter repeated twice.
// stringDoubler("Hello") == "H
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0..<n {
result += "\(i) "
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func firstUniqChar(string: String) -> Int {
var result = 0
var count = 0
for char in string {
if string.count(for: char) == 1 {
result = string.firstIndex(of: char)!
count += 1
break
}
}
return count == 0 ? -1 : result
}
func lengthOfLongestSubstring(string: String) -> Int {
var result = 0
var count = 0
var start = 0
var map = [Character: Int]()
for i in 0..<string.count {
if map[string[i]] != nil {
start = max(map[string[i]]! + 1, start)
}
map[string[i]] = i
count = i - start + 1
result = max(result, count)
}
return result
}
func firstUniqChar(string: String) -> Int {
var result = 0
var count = 0
var map = [Character: Int]()
for i in 0..<string.count {
if map[string[i]] != nil {
map[string[i]]! += 1
} else {
map[string[i]] = 1
}
}
for i in 0..<string.count {
if map[string[i]] == 1 {
result = i
count += 1
break
}
}
return count == 0 ? -1 : result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 3. Given a string s, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(string: String) -> Int {
var result = 0
var count = 0
for char in string {
if string.count(for: char) == 1 {
result = string.firstIndex(of: char)!
count += 1
break
}
}
return count == 0 ? -1 : result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 4. Given a string s, find the length of the longest substring without repeating characters.
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(string: String) -> Int {
var result = 0
var count = 0
var start = 0
var map = [Character: Int]()
for i in 0..<string.count {
if map[string[i]] != nil {
start = max(map[string[i]]! + 1, start)
}
map[string[i]] = i
count = i - start + 1
result = max(result, count)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 5. Given a string s, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(string: String) -> Int {
var result = 0
var count = 0
var map = [Character: Int]()
for i in 0..<string.count {
if map[string[i]] != nil {
map[string[i]]! += 1
} else {
map[string[i]] = 1
}
}
for i in 0..<string.count {
if map[string[i]] == 1 {
result = i
count += 1
break
}
}
return count == 0 ? -1 : result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 6. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// longest
return result.trim() // value of type 'String' has no member 'trim'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
if string.count(for: char) == 1 { // cannot call value of non-function type 'Int'
result = string.firstIndex(of: char)! // cannot assign value of type 'String.Index' to type 'Int'
if map[string[i]] != nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
start = max(map[string[i]]! + 1, start) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[string[i]] = i // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func firstUniqChar(string: String) -> Int { // invalid redeclaration of 'firstUniqChar(string:)'
if map[string[i]] != nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[string[i]]! += 1 // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[string[i]] = 1 // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if map[string[i]] == 1 { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, find out how many distinct characters does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, find out how many distinct characters does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, find out how many distinct characters does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.5
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, find out how many distinct characters does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.6
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, find out how many distinct characters does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.map { $0.toLowercase() }).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.7
// ------------------------------------------------------------------
return Set(string.map { $0.toLowercase() }).count // value of type 'String.Element' (aka 'Character') has no member 'toLowercase'
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for char in string {
set.insert(char)
}
return set.count
}
func longestSubstringWithoutRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
func longestSubstringWithRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for char in string {
set.insert(char)
}
return set.count
}
// 2. Given a string, find the longest substring without repeating characters.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestSubstringWithoutRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
// 3. Given a string, find the longest substring with repeating characters.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestSubstringWithRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
// 4. Given a string, find the longest substring with repeating characters.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestSubstringWithRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
// 5. Given a string, find the longest substring with repeating characters.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestSubstringWithRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
}
return string[left..<right]
}
// 6. Given a string, find the longest substring with repeating characters.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestSubstringWithRepeatingCharacters(string: String) -> String {
var set = Set<Character>()
var maxLength = 0
var left = 0
var right = 0
while (right < string.count) {
if !set.contains(string[right]) {
set.insert(string[right])
right += 1
maxLength = max(maxLength, right - left)
} else {
set.remove(string[left])
left += 1
}
if !set.contains(string[right]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(string[right]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.remove(string[left]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return string[left..<right] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if !set.contains(string[right]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(string[right]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.remove(string[left]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return string[left..<right] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func countDistinctCharacters(string: String) -> Int {
return Set(string).count
}
func longestPalindromicSubstring(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = string[i..<j]
if substring == substring.reversed() && substring.length > longest.length {
longest = substring
}
}
}
return longest
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string).count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// Given a string, find the longest palindromic substring.
// longestPalindromicSubstring(string: "abaxyzzyxf") == "xyzzyx"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "a"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "f"
// longestPalindromicSubstring(string: "abaxyzzyxf") == ""
func longestPalindromicSubstring(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = string[i..<j]
if substring == substring.reversed() && substring.length > longest.length {
longest = substring
}
}
}
return longest
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// Given a string, find the longest palindromic substring of it.
// longestPalindromicSubstring(string: "abaxyzzyxf") == "xyzzyx"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "a"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "f"
// longestPalindromicSubstring(string: "abaxyzzyxf") == ""
func longestPalindromicSubstring(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = string[i..<j]
if substring == substring.reversed() && substring.length > longest.length {
longest = substring
}
}
}
return longest
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.5
// Given a string, find the longest palindromic substring of it.
// longestPalindromicSubstring(string: "abaxyzzyxf") == "xyzzyx"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "a"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "f"
// longestPalindromicSubstring(string: "abaxyzzyxf") == ""
func longestPalindromicSubstring(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = string[i..<j]
if substring == substring.reversed() && substring.length > longest.length {
longest = substring
}
}
}
return longest
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.6
// Given a string, find the longest palindromic substring of it.
// longestPalindromicSubstring(string: "abaxyzzyxf") == "xyzzyx"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "a"
// longestPalindromicSubstring(string: "abaxyzzyxf") == "f"
// longestPalindromicSubstring(string: "abaxyzzyxf") == ""
func longestPal
let substring = string[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if substring == substring.reversed() && substring.length > longest.length { // value of type 'String' has no member 'length'
if substring == substring.reversed() && substring.length > longest.length { // cannot convert value of type 'ReversedCollection<String>' to expected argument type 'String'
if substring == substring.reversed() && substring.length > longest.length { // value of type 'String' has no member 'length'
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for c in string {
set.insert(c)
}
return set.count
}
func removeVowels(string: String) -> String {
var result = ""
for c in string {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
func removeSpaces(string: String) -> String {
var result = ""
for c in string {
if c != " " {
result += c
}
}
return result
}
func swapCase(string: String) -> String {
var result = ""
for c in string {
if c.isUpper {
result += c.lowerCased
} else {
result += c.upperCased
}
}
return result
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for c in string {
set.insert(c)
}
return set.count
}
// 2. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("Hey, I'm a coder") == "Hy, m coder"
func removeVowels(string: String) -> String {
var result = ""
for c in string {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// 3. Write a function that takes a string and returns a string with all the spaces removed.
// removeSpaces("Hello, world!") == "Helloworld!"
func removeSpaces(string: String) -> String {
var result = ""
for c in string {
if c != " " {
result += c
}
}
return result
}
// 4. Write a function that takes a string and returns a string with all the uppercase characters lowercase and all lowercase characters uppercase.
// swapCase("Hello, world!") == "hELLO, WORLD!"
func swapCase(string: String) -> String {
var result = ""
for c in string {
if c.isUpper {
result += c.lowerCased
} else {
result += c.upperCased
}
}
return result
}
// 5. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("Hey, I'm a coder") == "Hy, m coder"
func removeVowels(string: String) -> String {
var result = ""
for c in string {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// 6. Write a function that takes a string and returns a string with all the spaces removed.
// removeSpaces("Hello, world!") == "Helloworld!"
func removeSpaces(string: String) -> String {
var result = ""
for c in string {
if c != " " {
result += c
}
}
return result
}
// 7. Write a function that takes a string and returns a string with all the uppercase characters lowercase and all lowercase characters uppercase.
// swapCase("Hello, world!") == "hELLO, WORLD!"
func swapCase(string: String) -> String {
var result = ""
for c in string {
if c.isUpper {
result += c.lowerCased
} else {
result += c.upperCased
}
}
return result
}
// 8. Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("Hey, I'm a coder") == "Hy, m coder"
func removeVowels(string: String) -> String {
var result = ""
for c in string {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// 9. Write a function that takes a string and returns a string with all the spaces removed.
// removeSpaces("Hello, world!") == "Helloworld!"
func removeSpaces(string: String) -> String {
var result = ""
for c in string {
if c != " " {
result += c
}
}
return result
}
// 10. Write a function that takes a string and returns a string with all the uppercase characters lowercase and all lowercase characters uppercase.
result += c // cannot convert value of type 'Character' to expected argument type 'String'
result += c // cannot convert value of type 'Character' to expected argument type 'String'
if c.isUpper { // value of type 'Character' has no member 'isUpper'
result += c.lowerCased // value of type 'Character' has no member 'lowerCased'
result += c.upperCased // value of type 'Character' has no member 'upperCased'
func countDistinctCharacters(string: String) -> Int {
var chars = [Character]()
for c in string {
if !chars.contains(c) {
chars.append(c)
}
}
return chars.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var chars = [Character]()
for c in string {
if !chars.contains(c) {
chars.append(c)
}
}
return chars.count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var count = 0
var seen = Set<Character>()
for c in string {
if !seen.contains(c) {
count += 1
seen.insert(c)
}
}
return count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var seen = Set<Character>()
for c in string {
if !seen.contains(c) {
count += 1
seen.insert(c)
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
return Set(string.uppercase).count
}
func countLowercaseLetters(string: String) -> Int {
return string.count(for: .lowerCased)
}
func countUppercaseLetters(string: String) -> Int {
return string.count(for: .upperCased)
}
func countDigits(string: String) -> Int {
return string.count(for: .digit)
}
func countWords(string: String) -> Int {
return string.split(by: .whitespace).count
}
func countWordsExcludingPunctuation(string: String) -> Int {
return string.split(by: .whitespace).count
}
func countWordsExcludingPunctuationAndNumbers(string: String) -> Int {
return string.split(by: .whitespace).count
}
func countWordsExcludingPunctuationAndNumbersAndSpaces(string: String) -> Int {
return string.split(by: .whitespace).count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
return Set(string.uppercase).count
}
// 2. Given a string, find out how many lowercase letters does it consist of
// countLowercaseLetters(string: "xyzXYZ") == 3
// countLowercaseLetters(string: "Jerry") == 2
func countLowercaseLetters(string: String) -> Int {
return string.count(for: .lowerCased)
}
// 3. Given a string, find out how many uppercase letters does it consist of
// countUppercaseLetters(string: "xyzXYZ") == 3
// countUppercaseLetters(string: "Jerry") == 1
func countUppercaseLetters(string: String) -> Int {
return string.count(for: .upperCased)
}
// 4. Given a string, find out how many digits does it consist of
// countDigits(string: "xyzXYZ") == 0
// countDigits(string: "Jerry123") == 3
func countDigits(string: String) -> Int {
return string.count(for: .digit)
}
// 5. Given a string, find out how many words does it consist of
// countWords(string: "xyzXYZ") == 1
// countWords(string: "Jerry") == 1
// countWords(string: "Jerry,") == 2
// countWords(string: "Jerry, ") == 2
// countWords(string: "Jerry, 123") == 3
func countWords(string: String) -> Int {
return string.split(by: .whitespace).count
}
// 6. Given a string, find out how many words does it consist of, excluding punctuation
// countWordsExcludingPunctuation(string: "xyzXYZ") == 1
// countWordsExcludingPunctuation(string: "Jerry") == 1
// countWordsExcludingPunctuation(string: "Jerry,") == 1
// countWordsExcludingPunctuation(string: "Jerry, ") == 1
// countWordsExcludingPunctuation(string: "Jerry, 123") == 1
func countWordsExcludingPunctuation(string: String) -> Int {
return string.split(by: .whitespace).count
}
// 7. Given a string, find out how many words does it consist of, excluding punctuation and numbers
// countWordsExcludingPunctuationAndNumbers(string: "xyzXYZ") == 1
// countWordsExcludingPunctuationAndNumbers(string: "Jerry") == 1
// countWordsExcludingPunctuationAndNumbers(string: "Jerry,") == 1
// countWordsExcludingPunctuationAndNumbers(string: "Jerry, ") == 1
// countWordsExcludingPunctuationAndNumbers(string: "Jerry, 123") == 1
func countWordsExcludingPunctuationAndNumbers(string: String) -> Int {
return string.split(by: .whitespace).count
}
// 8. Given a string, find out how many words does it consist of, excluding punctuation, numbers and spaces
// countWordsExcludingPunctuationAndNumbersAndSpaces(string: "xyzXYZ") == 1
// countWordsExcludingPunctuationAndNumbersAndSpaces(string: "Jerry") == 1
// countWordsExcludingPunctuationAndNumbersAndSpaces(string: "Jerry,") == 1
// countWordsExcludingPunctuationAndNumbersAndSpaces(string: "Jerry, ") == 1
// countWordsExcludingPunctuationAndNumbersAndSpaces(string: "Jerry, 123") == 1
func countWordsExcludingPunctuationAndNumbersAndSpaces(string: String) -> Int {
return string.split(by: .whitespace).count
}
// 9. Given a string, find out how many words does it consist of, excluding punctuation, numbers, spaces and special characters
// countWordsExcludingPunctuationAndNumbersAndSpacesAndSpecialCharacters(string: "xyzXYZ") == 1
// countWordsEx
return Set(string.uppercase).count // value of type 'String' has no member 'uppercase'
return string.count(for: .lowerCased) // cannot call value of non-function type 'Int'
return string.count(for: .lowerCased) // cannot infer contextual base in reference to member 'lowerCased'
return string.count(for: .upperCased) // cannot infer contextual base in reference to member 'upperCased'
return string.count(for: .upperCased) // cannot call value of non-function type 'Int'
return string.count(for: .digit) // cannot infer contextual base in reference to member 'digit'
return string.count(for: .digit) // cannot call value of non-function type 'Int'
return string.split(by: .whitespace).count // no exact matches in call to instance method 'split'
return string.split(by: .whitespace).count // cannot infer contextual base in reference to member 'whitespace'
return string.split(by: .whitespace).count // no exact matches in call to instance method 'split'
return string.split(by: .whitespace).count // cannot infer contextual base in reference to member 'whitespace'
return string.split(by: .whitespace).count // cannot infer contextual base in reference to member 'whitespace'
return string.split(by: .whitespace).count // no exact matches in call to instance method 'split'
return string.split(by: .whitespace).count // cannot infer contextual base in reference to member 'whitespace'
return string.split(by: .whitespace).count // no exact matches in call to instance method 'split'
func countDistinctCharacters(string: String) -> Int {
var chars = Set<Character>()
for char in string {
chars.insert(char)
}
return chars.count
}
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var chars = Set<Character>()
for char in string {
chars.insert(char)
}
return chars.count
}
// 2. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 3. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 4. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 5. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 6. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 7. Given a string, find the longest palindromic substring in it.
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func longestPalindrome(string: String) -> String {
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
var substring = string[i..<j]
if substring ==
var substring = string[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if substring == substring.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for c in string {
set.insert(c)
}
return set.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var set = Set<Character>()
for c in string {
set.insert(c)
}
return set.count
}
// 2. Write a function that takes a string and returns the number of words in the string.
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
// countWords("Hello world!!") == 2
// countWords("Hello world!!!") == 2
// countWords("Hello world!!!!") == 2
// countWords("Hello world!!!!!") == 2
// countWords("Hello world!!!!!!") == 2
// countWords("Hello world!!!!!!!") == 2
// countWords("Hello world!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") == 2
// countWords("Hello world!
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.split(separator: " ").map { $0.trim() }
var result = [Int]()
var currentBeat = 0
for note in notes {
switch note {
case "o":
currentBeat += 4
result.append(currentBeat)
case "o|":
currentBeat += 2
result.append(currentBeat)
case ".|":
currentBeat += 1
result.append(currentBeat)
default:
break
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.split(separator: " ").map { $0.trim() }
var result = [Int]()
var currentBeat = 0
for note in notes {
switch note {
case "o":
currentBeat += 4
result.append(currentBeat)
case "o|":
currentBeat += 2
result.append(currentBeat)
case ".|":
currentBeat += 1
result.append(currentBeat)
default:
break
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
let notes = musicString.split(separator: " ").map { $0.trim() } // reference to member 'trim' cannot be resolved without a contextual type
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentBeat)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentBeat)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for note in musicString {
if note == "o" {
currentBeat += 4
} else if note == "o|" {
currentBeat += 2
} else if note == ".|" {
currentBeat += 1
}
result.append(currentBeat)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for note in musicString {
if note == "o" {
currentBeat += 4
} else if note == "o|" {
currentBeat += 2
} else if note == ".|" {
currentBeat += 1
}
result.append(currentBeat)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
} else if note == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if note == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
var currentLength = 0
for char in musicString {
if char == "o" {
currentLength = 4
} else if char == "o|" {
currentLength = 2
} else if char == ".|" {
currentLength = 1
}
currentBeat += 1
currentNote += 1
if currentBeat == currentLength {
currentBeat = 0
currentNote = 0
result.append(currentNote)
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
var currentLength = 0
for char in musicString {
if char == "o" {
currentLength = 4
} else if char == "o|" {
currentLength = 2
} else if char == ".|" {
currentLength = 1
}
currentBeat += 1
currentNote += 1
if currentBeat == currentLength {
currentBeat = 0
currentNote = 0
result.append(currentNote)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
func highestScoringWord(word: String) -> String {
var result = ""
var currentScore = 0
var currentWord = ""
for char in word {
if char == " " {
if currentScore < score(currentWord) {
currentScore = score(currentWord)
result = currentWord
}
currentWord = ""
} else {
currentWord += char
}
}
if currentScore < score(currentWord) {
currentScore = score(currentWord)
result = currentWord
}
return result
}
func descendingOrder(n: Int) -> Int {
var result = 0
var current = n
var digits = [Int]()
while current > 0 {
digits.append(current % 10)
current /= 10
}
for _ in digits {
var max = 0
for digit in digits {
if digit > max {
max = digit
}
}
result = result * 10 + max
digits.remove(at: digits.firstIndex(of: max)!)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// https://www.codewars.com/kata/56f699cd9400f5b7d000b887/train/swift
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// highestScoringWord("man i need a taxi up to ubud") == "taxi"
// highestScoringWord("what time are we climbing up to the volcano") == "volcano"
// highestScoringWord("take me to semynak") == "semynak"
func highestScoringWord(word: String) -> String {
var result = ""
var currentScore = 0
var currentWord = ""
for char in word {
if char == " " {
if currentScore < score(currentWord) {
currentScore = score(currentWord)
result = currentWord
}
currentWord = ""
} else {
currentWord += char
}
}
if currentScore < score(currentWord) {
currentScore = score(currentWord)
result = currentWord
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/swift
// Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
// DescendingOrder(123) == 321
// DescendingOrder(123456789) == 987654321
func descendingOrder(n: Int) -> Int {
var result = 0
var current = n
var digits = [Int]()
while current > 0 {
digits.append(current % 10)
current /= 10
}
for _ in digits {
var max = 0
for digit in digits {
if digit > max {
max = digit
}
}
result = result * 10 + max
digits.remove(at: digits.firstIndex(of: max)!)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/swift
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
if currentScore < score(currentWord) { // cannot find 'score' in scope
currentScore = score(currentWord) // cannot find 'score' in scope
currentWord += char // cannot convert value of type 'Character' to expected argument type 'String'
if currentScore < score(currentWord) { // cannot find 'score' in scope
currentScore = score(currentWord) // cannot find 'score' in scope
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for note in musicString {
if note == "o" {
currentBeat += 4
result.append(currentBeat)
} else if note == "o|" {
currentBeat += 2
result.append(currentBeat)
} else if note == ".|" {
currentBeat += 1
result.append(currentBeat)
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for note in musicString {
if note == "o" {
currentBeat += 4
result.append(currentBeat)
} else if note == "o|" {
currentBeat += 2
result.append(currentBeat)
} else if note == ".|" {
currentBeat += 1
result.append(currentBeat)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------
} else if note == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if note == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.split(separator: " ").map { $0.trim() }
var result = [Int]()
var beat = 0
for note in notes {
switch note {
case "o":
beat += 4
result.append(beat)
case "o|":
beat += 2
result.append(beat)
case ".|":
beat += 1
result.append(beat)
default:
break
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.split(separator: " ").map { $0.trim() }
var result = [Int]()
var beat = 0
for note in notes {
switch note {
case "o":
beat += 4
result.append(beat)
case "o|":
beat += 2
result.append(beat)
case ".|":
beat += 1
result.append(beat)
default:
break
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
let notes = musicString.split(separator: " ").map { $0.trim() } // reference to member 'trim' cannot be resolved without a contextual type
func parseMusic(musicString: String) -> [Int] {
let arr = musicString.split(separator: " ").map { $0.trim() }
var res = [Int]()
for i in arr {
switch i {
case "o":
res.append(4)
case "o|":
res.append(2)
case ".|":
res.append(1)
default:
res.append(0)
}
}
return res
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func hammingWeight(n: Int) -> Int {
return String(UInt32(n)).count(of: "1")
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let arr = musicString.split(separator: " ").map { $0.trim() }
var res = [Int]()
for i in arr {
switch i {
case "o":
res.append(4)
case "o|":
res.append(2)
case ".|":
res.append(1)
default:
res.append(0)
}
}
return res
}
// 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 11. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 00000000000000000000000000001011, return 3.
//
// Note:
// - `popcount` is a built-in function in C++, Java, Go, JavaScript, PHP and Python, but not in C.
// - The best solution to this problem is probably a built-in function in some languages.
// - This question is the same as 191: https://leetcode.com/problems/number-of-1-bits/
func hammingWeight(n: Int) -> Int {
return String(UInt32(n)).count(of: "1")
}
// 12. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 00000000000000000000000000001011, return 3.
//
// Note:
// - `popcount` is a built-in function in C++, Java, Go, JavaScript, PHP and Python, but not in C.
// - The best solution to this problem is probably a built-in function in some languages.
// - This question is the same as 191: https://leetcode.com/problems/number-of-1-bits/
func hammingWeight(n: Int) -> Int {
return String(UInt32(n)).count(of: "1")
}
// 13. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 00000000000000000000000000001011, return 3.
//
// Note:
// - `popcount` is a built-in function in C++, Java, Go, JavaScript, PHP and Python, but not in C.
// - The best solution to this problem is probably a built-in function in some languages.
// - This question is the same as 191: https://leetcode.com/problems/number-of-1-bits/
func hammingWeight(n: Int) -> Int {
return String(UInt32(n)).count(of: "1")
}
// 14. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 00000000000000000000000000001011, return 3.
//
// Note:
// - `popcount` is a built-in function in C++, Java, Go, JavaScript, PHP and Python, but not in C.
// - The best solution to this problem is probably a built-in function in some languages.
// - This question is the same as 191: https://leetcode.com/problems/number-of-1-bits/
func hammingWeight(n: Int) -> Int {
return String(UInt32(n)).count(of: "1")
}
// 15. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 0000000000000
let arr = musicString.split(separator: " ").map { $0.trim() } // reference to member 'trim' cannot be resolved without a contextual type
return String(UInt32(n)).count(of: "1") // cannot call value of non-function type 'Int'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
function findOdd(A) {
return A.find(a => A.filter(b => b === a).length % 2 !== 0)
}
function high(x){
let alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
let words = x.split(" ")
let scores = words.map(word => {
let score = 0
for (let i = 0; i < word.length; i++) {
score += alphabet.indexOf(word[i]) + 1
}
return score
})
return words[scores.indexOf(Math.max(...scores))]
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
var currentNote = 0
for char in musicString {
if char == "o" {
currentBeat += 4
currentNote += 1
} else if char == "o|" {
currentBeat += 2
currentNote += 1
} else if char == ".|" {
currentBeat += 1
currentNote += 1
}
result.append(currentNote)
}
return result
}
// 2.
// Given an array of integers, find the one that appears an odd number of times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
// Notes
// There will always be only one integer that appears an odd number of times.
// Int32 is not allowed for the language
// Function name should be findOdd
function findOdd(A) {
return A.find(a => A.filter(b => b === a).length % 2 !== 0)
}
// 3.
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Examples
// high("hello") == "hello"
// high("hey") == "hey"
// high("") == ""
// high("a") == "a"
// high("bb") == "bb"
// high("code") == "code"
// high("aewfauhq3yh8y3h5dfjhy3y8573y8573y8573") == "aewfauhq3yh8y3h5dfjhy3y8573y8573"
function high(x){
let alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
let words = x.split(" ")
let scores = words.map(word => {
let score = 0
for (let i = 0; i < word.length; i++) {
score += alphabet.indexOf(word[i]) + 1
}
return score
})
return words[scores.indexOf(Math.max(...scores))]
}
// 4.
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Examples
// high("hello") == "hello"
// high("hey") == "hey"
// high("") == ""
// high("a") == "a"
// high("bb") == "bb"
// high("code") == "code"
// high("aewfauhq3yh8y3h5dfjhy3y8573y8573y8573") == "aewfauhq3yh8y3h5dfjhy3y8573
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
function findOdd(A) { // expansion of macro 'function()' requires leading '#'
function findOdd(A) { // generic parameter 'T' could not be inferred
function findOdd(A) { // consecutive statements on a line must be separated by ';'
function findOdd(A) { // cannot find 'A' in scope
function findOdd(A) { // cannot find 'findOdd' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'a' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'b' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'a' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // argument type 'Int' expected to be an instance of a class or class-constrained type
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'A' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'A' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // argument type 'Int' expected to be an instance of a class or class-constrained type
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find operator '=>' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find 'b' in scope
return A.find(a => A.filter(b => b === a).length % 2 !== 0) // cannot find operator '=>' in scope
function high(x){ // cannot find 'x' in scope
function high(x){ // expansion of macro 'function()' requires leading '#'
function high(x){ // cannot find 'high' in scope
function high(x){ // generic parameter 'T' could not be inferred
function high(x){ // consecutive statements on a line must be separated by ';'
let alphabet = "abcdefghijklmnopqrstuvwxyz".split("") // missing argument label 'separator:' in call
let words = x.split(" ") // cannot find 'x' in scope
let scores = words.map(word => { // cannot find 'word' in scope
let scores = words.map(word => { // cannot find operator '=>' in scope
for (let i = 0; i < word.length; i++) { // C-style for statement has been removed in Swift 3
score += alphabet.indexOf(word[i]) + 1 // cannot find 'word' in scope
score += alphabet.indexOf(word[i]) + 1 // cannot find 'i' in scope
return words[scores.indexOf(Math.max(...scores))] // cannot find 'Math' in scope
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------
if string[index...].contains(substring) { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index != -1 {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count))
if index != -1 {
count += 1
}
}
return count
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index != -1 {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count))
if index != -1 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ---------------------------------------
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count)) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count)) // cannot infer contextual base in reference to member 'caseInsensitive'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count)) // extra arguments at positions #2, #3 in call
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index + 1 ... string.count)) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
if !isVowel(char: char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index))
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index))
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 18. Write a function that takes a string and returns a new string with all the vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
//
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot infer contextual base in reference to member 'caseInsensitive'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // extra arguments at positions #2, #3 in call
if index == nil { // comparing non-optional value of type 'Int' to 'nil' always returns false
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, in: string[..<index + substring.count])
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, in: string[..<index + substring.count])
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.1
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
//
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET tEST IS hHI"
// " space here " ==> "SPACE HERE "
// " spaces here " ==> "sPACES HERE "
//
// Solution:
// 1. Split the string into words.
// 2. Reverse the order of the words.
// 3. Change the case of the words.
// 4. Join the words back into a string.
//
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2
// Given a string and a non-negative number, return a larger string that is n copies of the original string.
//
// Example:
// stringTimes("Hi", 2) == "HiHi"
// stringTimes("Hi", 3) == "HiHiHi"
// stringTimes("Hi", 1) == "Hi"
//
// Solution:
// 1. Split the string into words.
// 2. Join the words back into a string.
//
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).
//
// Example:
//
// isNotNotIsNot("not not is not") → true
// isNotNotIsNot("is not is not") → false
// isNotNotIsNot("is is not not") → false
//
// Solution:
// 1. Split the string into words.
// 2. Count the number of "is" and "not" words.
// 3. Return true if the counts are equal.
//
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// Given a string, return the number of times that a substring appears in the string, without the substring being counted multiple times.
// (It's ok if the substring appears multiple times in the string.)
//
// Example:
//
// substrCount("aba") → 2
// substrCount("abab") → 4
// substrCount("abcabcabc") → 9
//
// Solution:
// 1. Split the string into words.
// 2. Count the number of times each word appears.
// 3. Return the sum of the counts.
//
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.5
// Given a string, return the length of the largest "block" in the string.
// A block is a run of adjacent chars that are the same.
//
// Example:
//
// maxBlock("hoopla") → 2
// maxBlock("abbCCCddBBBxx")
index = string.index(of: substring, in: string[..<index + substring.count]) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.index(of: substring, in: string[..<index + substring.count]) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
index = string.index(of: substring, in: string[..<index + substring.count]) // extra argument 'in' in call
index = string.index(of: substring, in: string[..<index + substring.count]) // cannot convert value of type 'PartialRangeUpTo<Int>' to expected argument type 'Int'
if index == nil { // comparing non-optional value of type 'Int' to 'nil' always returns false
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index))
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index))
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
// 2. Write a function that takes a string and returns a string with the letters in alphabetical order.
// alphabetize("hello") == "ehllo"
// alphabetize("") == ""
// alphabetize("a") == "a"
// alphabetize("abc") == "abc"
// alphabetize("bob") == "bba"
// alphabetize("zoo") == "ooz"
// alphabetize("aardvark") == "aaarrdddvvvkkkzzz"
// alphabetize("zooom") == "oomz"
// alphabetize("zooomm") == "oommz"
// alphabetize("zoooomm") == "oommzoo"
// alphabetize("zoooommoo") == "oommzoooom"
// alphabetize("zoooommooz") == "oommzoooomz"
// alphabetize("zoooommoozoo") == "oommzoooomzoo"
// alphabetize("zoooommoozooom") == "oommzoooomzooom"
// alphabetize("zoooommoozooomm") == "oommzoooomzooomm"
// alphabetize("zoooommoozooommz") == "oommzoooomzooommz"
// alphabetize("zoooommoozooommzz") == "oommzoooomzooommzz"
// alphabetize("zoooommoozooommzzz" == "oommzoooomzooommzzz"
// alphabetize("zoooommoozooommzzzz" == "oommzoooomzooommzzzz"
// alphabetize("zoooommoozooommzzzzz" == "oommzoooomzooommzzzzz"
// alphabetize("zoooommoozooommzzzzzz" == "oommzoooomzooommzzzzzz"
// alphabetize("zoooommoozooommzzzzzzz" == "oommzoooomzooommzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzz" == "oommzoooomzooommzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzz" == "oommzoooomzooommzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzzzzzz" == "oommzoooomzooommzzzzzzzzzzzzzzzz"
// alphabetize("zoooommoozooommzzzzzzzzzzzzzzzzz" == "oommz
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot infer contextual base in reference to member 'caseInsensitive'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.firstIndex(of: substring, options: .caseInsensitive, range: (index, string.count - index)) // extra arguments at positions #2, #3 in call
if index == nil { // comparing non-optional value of type 'Int' to 'nil' always returns false
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
var index = 0
while index < string.count {
if string.index(of: substring, in: string[index...]) == index {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
func isPalindrome(string: String) -> Bool {
var left = 0
var right = string.count - 1
while left < right {
if string[left] != string[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
var index = 0
while index < string.count {
if string.index(of: substring, in: string[index...]) == index {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(string: String) -> Bool {
var left = 0
var right = string.count - 1
while left < right {
if string[left] != string[right] {
return false
}
left += 1
right -= 1
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(string: String) -> Bool {
var left = 0
var right = string.count - 1
while left < right {
if string[left] != string[right] {
return false
}
left += 1
right -= 1
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have a dog") == " hv dg"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
if string.index(of: substring, in: string[index...]) == index { // cannot convert value of type 'String.Index?' to expected argument type 'Int'
if string.index(of: substring, in: string[index...]) == index { // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
if string.index(of: substring, in: string[index...]) == index { // extra argument 'in' in call
count += 1 // left side of mutating operator isn't mutable: 'count' is a 'let' constant
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if string[left] != string[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[left] != string[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
let index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
let index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
if string[index...].contains(substring) { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
count += 1 // left side of mutating operator isn't mutable: 'count' is a 'let' constant
index += substring.count // left side of mutating operator isn't mutable: 'index' is a 'let' constant
index += 1 // left side of mutating operator isn't mutable: 'index' is a 'let' constant
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
if string[index...].contains(substring) {
count += 1
index += substring.count
} else {
index += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
// removeVowels("bcdfghjklmnpqrstvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz") == "bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz"
// removeVowels("bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz") == "bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz"
// removeVowels("bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz") == "bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz"
// removeVowels("bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz") == "bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyz"
// removeVowels("bcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqrstvwxyzBcdfghjklmnpqr
if string[index...].contains(substring) { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
let index = 0
while index < string.count {
let nextIndex = string.index(of: substring, in: string[index...])
if nextIndex == nil {
break
}
count += 1
index = nextIndex!
}
return count
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func swapCase(string: String) -> String {
return string.map {
if $0.isUpperCase {
return $0.lowercased
} else {
return $0.uppercased
}
}.join()
}
func trim(string: String) -> String {
return string.trim()
}
func trimWhitespace(string: String) -> String {
return string.trim()
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
let index = 0
while index < string.count {
let nextIndex = string.index(of: substring, in: string[index...])
if nextIndex == nil {
break
}
count += 1
index = nextIndex!
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.2
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(string: String) -> String {
return string.reversed().join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.3
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string with all uppercase characters replaced with lowercase characters and vice versa.
// swapCase("Hello, World!") == "hELLO, wORLD!"
// swapCase("") == ""
func swapCase(string: String) -> String {
return string.map {
if $0.isUpperCase {
return $0.lowercased
} else {
return $0.uppercased
}
}.join()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.4
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string with leading and trailing spaces removed.
// trim(" Hello, World! ") == "Hello, World!"
// trim("") == ""
func trim(string: String) -> String {
return string.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.5
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string with leading and trailing whitespace removed.
// trimWhitespace(" Hello, World! ") == "Hello, World!"
// trimWhitespace("") == ""
func trimWhitespace(string: String) -> String {
return string.trim()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.1.6
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string with leading and trailing whitespace removed.
// trimWhitespace(" Hello, World! ") == "Hello, World!"
// trimWhitespace("") == ""
func trimWhitespace(string: String) -> String {
return string.trim()
}
// ---------------------
let nextIndex = string.index(of: substring, in: string[index...]) // extra argument 'in' in call
let nextIndex = string.index(of: substring, in: string[index...]) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
count += 1 // left side of mutating operator isn't mutable: 'count' is a 'let' constant
index = nextIndex! // cannot assign to value: 'index' is a 'let' constant
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
if $0.isUpperCase { // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
}.join() // value of type 'Array<_>' has no member 'join'
return string.trim() // value of type 'String' has no member 'trim'
return string.trim() // value of type 'String' has no member 'trim'
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true)
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = 0
var index = 0
while index < string.count {
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true)
if index == nil {
break
}
count += 1
index += substring.count
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("abracadabra") == "brcdbrkr"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome("") == true
// isPalindrome("a") == true
// isPalindrome("ab") == false
// isPalindrome("aba") == true
// isPalindrome("abba") == true
// isPalindrome("abccba") == true
// isPalindrome("abccd") == false
// isPalindrome("abccdba") == true
// isPalindrome("abccddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abccdddba") == true
// isPalindrome("abcc
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true) // cannot infer contextual base in reference to member 'ignoreCase'
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.firstIndex(of: substring, options: .ignoreCase, range: (index ... string.count), containing: true) // extra arguments at positions #2, #3, #4 in call
if index == nil { // comparing non-optional value of type 'Int' to 'nil' always returns false
count += 1 // left side of mutating operator isn't mutable: 'count' is a 'let' constant
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return String(sorted)
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return String(sorted)
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return String(sorted) // no exact matches in call to initializer
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return String(sorted)
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return String(sorted)
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return String(sorted) // no exact matches in call to initializer
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { Int($0) }
return String(nums.sorted())
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { Int($0) }
return String(nums.sorted())
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return String(nums.sorted()) // no exact matches in call to initializer
return String(nums.sorted()) // referencing instance method 'sorted()' on 'Sequence' requires that 'Int?' conform to 'Comparable'
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return String(sortedNumbers)
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return String(sortedNumbers)
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return String(sortedNumbers) // no exact matches in call to initializer
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return String(sortedNumbers)
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return String(sortedNumbers)
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return String(sortedNumbers) // no exact matches in call to initializer
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return sorted.map { $0 }.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return sorted.map { $0 }.joined(separator: " ")
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.map { $0 }.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.map { $0 }.joined(separator: " ")
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return sorted.map { $0 }.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sorted = numbers.split(separator: " ").sorted()
return sorted.map { $0 }.joined(separator: " ")
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let sortedNumbers = numbers.split(separator: " ").sorted()
return sortedNumbers.joined(separator: " ")
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var min = Double.infinity
var min1 = Double.infinity
var min2 = Double.infinity
var min3 = Double.infinity
for i in 0..<numbers.count {
if numbers[i] < min {
min3 = min2
min2 = min1
min1 = min
min = numbers[i]
} else if numbers[i] < min1 {
min3 = min2
min2 = min1
min1 = numbers[i]
} else if numbers[i] < min2 {
min3 = min2
min2 = numbers[i]
} else if numbers[i] < min3 {
min3 = numbers[i]
}
}
return (min, min3)
}
func mostFrequentCharacter(string: String) -> String {
var count = [Int](repeating: 0, count: 256)
for i in string.utf8.map {
count[i] += 1
}
var max = 0
var maxChar = ""
for i in 0..<count.count {
if count[i] > max {
max = count[i]
maxChar = String(c: i)
}
}
return maxChar
}
func isPalindrome(string: String) -> Bool {
var reversed = ""
for i in string.reversed() {
reversed += i
}
return string == reversed
}
func leastFrequentCharacter(string: String) -> String {
var count = [Int](repeating: 0, count: 256)
for i in string.utf8.map {
count[i] += 1
}
var min = Int.max
var minChar = ""
for i in 0..<count.count {
if count[i] < min {
min = count[i]
minChar = String(c: i)
}
}
return minChar
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var min = Double.infinity
var min1 = Double.infinity
var min2 = Double.infinity
var min3 = Double.infinity
for i in 0..<numbers.count {
if numbers[i] < min {
min3 = min2
min2 = min1
min1 = min
min = numbers[i]
} else if numbers[i] < min1 {
min3 = min2
min2 = min1
min1 = numbers[i]
} else if numbers[i] < min2 {
min3 = min2
min2 = numbers[i]
} else if numbers[i] < min3 {
min3 = numbers[i]
}
}
return (min, min3)
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as a parameter and returns the letter that appears the most
// often.
// mostFrequentCharacter("abracadabra") == "a"
func mostFrequentCharacter(string: String) -> String {
var count = [Int](repeating: 0, count: 256)
for i in string.utf8.map {
count[i] += 1
}
var max = 0
var maxChar = ""
for i in 0..<count.count {
if count[i] > max {
max = count[i]
maxChar = String(c: i)
}
}
return maxChar
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string as a parameter and returns true if the string is a palindrome,
// false otherwise.
// isPalindrome("abba") == true
// isPalindrome("abab") == false
func isPalindrome(string: String) -> Bool {
var reversed = ""
for i in string.reversed() {
reversed += i
}
return string == reversed
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string as a parameter and returns the letter that appears the least
// often.
// leastFrequentCharacter("abracadabra") == "a"
func leastFrequentCharacter(string: String) -> String {
var count = [Int](repeating: 0, count: 256)
for i in string.utf8.map {
count[i] += 1
}
var min = Int.max
var minChar = ""
for i in 0..<count.count {
if count[i] < min {
min = count[i]
minChar = String(c: i)
}
}
return minChar
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string as a parameter and returns the letter that appears the most
// often.
// mostFrequentCharacter("abracadabra") == "a"
func mostFrequentCharacter(string: String) -> String {
var count = [Int](repeating: 0, count: 256)
for i in string.utf8.map {
count[i] += 1
}
var max = 0
var maxChar = ""
for i in 0..<count.count {
if count[i] > max {
max = count[i]
maxChar = String(c: i)
}
for i in string.utf8.map { // for-in loop requires '((String.UTF8View.Element) throws -> T) throws -> [T]' (aka '((UInt8) throws -> T) throws -> Array<T>') to conform to 'Sequence'
for i in string.utf8.map { // generic parameter 'T' could not be inferred
maxChar = String(c: i) // no exact matches in call to initializer
reversed += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
for i in string.utf8.map { // for-in loop requires '((String.UTF8View.Element) throws -> T) throws -> [T]' (aka '((UInt8) throws -> T) throws -> Array<T>') to conform to 'Sequence'
for i in string.utf8.map { // generic parameter 'T' could not be inferred
minChar = String(c: i) // no exact matches in call to initializer
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted[0]
let last = sorted.last!
let diff = first - last
let index = sorted.firstIndex(of: first)
let result = sorted[index!]
let result2 = sorted[index! + 1]
return (result, result2)
}
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
return result
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let first = sorted[0]
let last = sorted.last!
let diff = first - last
let index = sorted.firstIndex(of: first)
let result = sorted[index!]
let result2 = sorted[index! + 1]
return (result, result2)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.1.1
// Write a function that takes a string as an argument and returns a new string that contains every other character in the
// original string.
// everyOtherCharacter("Codecademy") == "Cdmdm"
// everyOtherCharacter("Hello world!") == "Hlo wrd!"
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.1.2
// Write a function that takes a string as an argument and returns a new string that contains every other character in the
// original string.
// everyOtherCharacter("Codecademy") == "Cdmdm"
// everyOtherCharacter("Hello world!") == "Hlo wrd!"
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.1.3
// Write a function that takes a string as an argument and returns a new string that contains every other character in the
// original string.
// everyOtherCharacter("Codecademy") == "Cdmdm"
// everyOtherCharacter("Hello world!") == "Hlo wrd!"
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.1.4
// Write a function that takes a string as an argument and returns a new string that contains every other character in the
// original string.
// everyOtherCharacter("Codecademy") == "Cdmdm"
// everyOtherCharacter("Hello world!") == "Hlo wrd!"
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.1.5
// Write a function that takes a string as an argument and returns a new string that contains every other character in the
// original string.
// everyOtherCharacter("Codecademy") == "Cdmdm"
// everyOtherCharacter("Hello world!") == "Hlo wrd!"
func everyOtherCharacter(string: String) -> String {
let result = ""
for i in 0..<string.count {
if i % 2 == 0 {
result += string[i]
}
}
let diff = first - last // initialization of immutable value 'diff' was never used; consider replacing with assignment to '_' or removing it
result += string[i] // no exact matches in call to subscript
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var min = Double.infinity
var min1 = Double.infinity
var min2 = Double.infinity
var min3 = Double.infinity
for i in numbers {
if i < min {
min3 = min2
min2 = min1
min1 = min
min = i
} else if i < min1 {
min3 = min2
min2 = min1
min1 = i
} else if i < min2 {
min3 = min2
min2 = i
} else if i < min3 {
min3 = i
}
}
return (min, min3)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var min = Double.infinity
var min1 = Double.infinity
var min2 = Double.infinity
var min3 = Double.infinity
for i in numbers {
if i < min {
min3 = min2
min2 = min1
min1 = min
min = i
} else if i < min1 {
min3 = min2
min2 = min1
min1 = i
} else if i < min2 {
min3 = min2
min2 = i
} else if i < min3 {
min3 = i
}
}
return (min, min3)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair: (Double, Double) = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
func countOnesUnsigned(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair: (Double, Double) = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
// 1.1.11
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 1.1.12
// Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// The 32-bit integer 11 has binary representation
// 00000000000000000000000000001011
// so the function should return 3.
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 1.1.13
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011, so the function should return 3.
func countOnesUnsigned(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 1.1.14
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011, so the function should return 3.
func countOnesUnsigned(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 1.1.15
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011, so the function should return 3.
func countOnesUnsigned(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 1.1.16
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001011, so the function should return 3.
func countOnesUnsigned(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 1.1.17
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
count += n & 1 // cannot convert value of type 'UInt' to expected argument type 'Int'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair: (Double, Double) = (Double.infinity, Double.infinity)
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair: (Double, Double) = (Double.infinity, Double.infinity)
for i in 0..<numbers.count - 1 {
for j in i + 1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Given an array of integers, return a new array with each value doubled.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Given two strings, append them together (known as "concatenation") and return the result. However, if the strings are different lengths, omit chars from the longer string so it is the same length as the shorter string. So "Hello" and "Hi" yield "loHi". The strings may be any length.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Given two strings, append them together (known as "concatenation") and return the result. However, if the strings are different lengths, omit chars from the longer string so it is the same length as the shorter string. So
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minPair = (numbers[i], numbers[j])
}
}
}
return minPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minPair = (numbers[i], numbers[j])
}
}
}
return minPair
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
func sumOfPositives(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number > 0 {
sum += number
}
}
return sum
}
func largestDifference(numbers: [Int]) -> Int {
var max = Int.min
var min = Int.max
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
func mean(numbers: [Int]) -> Double {
var sum = 0
for number in numbers {
sum += number
}
return Double(sum) / Double(numbers.count)
}
func median(numbers: [Int]) -> Double {
var sortedNumbers = numbers.sorted()
if sortedNumbers.count % 2 == 0 {
return Double(sortedNumbers[sortedNumbers.count/2-1] + sortedNumbers[sortedNumbers.count/2]) / 2
} else {
return Double(sortedNumbers[sortedNumbers.count/2])
}
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minDiffPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count-1 {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minDiffPair = (numbers[i], numbers[j])
}
}
}
return minDiffPair
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Given an array of integers, return the sum of all the positive integers in the array.
// sumOfPositives([1, 2, 3, -1, -2, -3]) == 6
// sumOfPositives([-1, 2, 3, -1, -2, -3]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number > 0 {
sum += number
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Given an array of integers, return the difference between the largest and smallest integers in the array.
// largestDifference([1, 2, 3, 4, 5]) == 4
// largestDifference([5, 4, 3, 2, 1]) == 4
func largestDifference(numbers: [Int]) -> Int {
var max = Int.min
var min = Int.max
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Given an array of integers, return the mean (average) of the integers.
// mean([1, 2, 3, 4, 5]) == 3
// mean([1, 2, 3, 4, 5, 6]) == 3.5
func mean(numbers: [Int]) -> Double {
var sum = 0
for number in numbers {
sum += number
}
return Double(sum) / Double(numbers.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Given an array of integers, return the median (middle) value of the integers.
// median([1, 2, 3, 4, 5]) == 3
// median([1, 2, 3, 4, 5, 6]) == 3.5
func median(numbers: [Int]) -> Double {
var sortedNumbers = numbers.sorted()
if sortedNumbers.count % 2 == 0 {
return Double(sortedNumbers[sortedNumbers.count/2-1] + sortedNumbers[sortedNumbers.count/2]) / 2
} else {
return Double(sortedNumbers[sortedNumbers.count/2])
}
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Given an array of integers, return the mode (most common number) of the integers.
// mode([1, 2, 3, 4, 5]) == 1
// mode([1, 2, 3, 4, 5, 6]) == 1
// mode([1, 2, 3, 3, 3, 4, 5]) == 3
func mode(numbers: [Int])
var sortedNumbers = numbers.sorted() // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var first = 0
var second = 0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
first = i
second = j
}
}
}
return (numbers[first], numbers[second])
}
func findFirstUniqueChar(s: String) -> Int {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
var index = chars.firstIndex(of: char)!
counts[index] += 1
}
}
for i in 0..<counts.count {
if counts[i] == 1 {
return i
}
}
return -1
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var first = 0
var second = 0
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
first = i
second = j
}
}
}
return (numbers[first], numbers[second])
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.3
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// s = "leetcode"
// findFirstUniqueChar(s: s) == 0
// s = "loveleetcode"
// findFirstUniqueChar(s: s) == 2
func findFirstUniqueChar(s: String) -> Int {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
var index = chars.firstIndex(of: char)!
counts[index] += 1
}
}
for i in 0..<counts.count {
if counts[i] == 1 {
return i
}
}
return -1
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.4
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// s = "leetcode"
// findFirstUniqueChar(s: s) == 0
// s = "loveleetcode"
// findFirstUniqueChar(s: s) == 2
func findFirstUniqueChar(s: String) -> Int {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
var index = chars.firstIndex(of: char)!
counts[index] += 1
}
}
for i in 0..<counts.count {
if counts[i] == 1 {
return i
}
}
return -1
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.5
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// s = "leetcode"
// findFirstUniqueChar(s: s) == 0
// s = "loveleetcode"
// findFirstUniqueChar(s: s) == 2
func findFirstUniqueChar(s: String) -> Int {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
var index = chars.firstIndex(of: char)!
counts[index] += 1
}
}
for i in 0..<counts.count {
if counts[i] == 1 {
return i
}
}
return -1
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.2.6
// Given a string, find the first non-
var index = chars.firstIndex(of: char)! // variable 'index' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minPair = (numbers[i], numbers[j])
}
}
}
return minPair
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var minDiff = Double.infinity
var minPair = (Double.infinity, Double.infinity)
for i in 0..<numbers.count {
for j in i+1..<numbers.count {
let diff = abs(numbers[i] - numbers[j])
if diff < minDiff {
minDiff = diff
minPair = (numbers[i], numbers[j])
}
}
}
return minPair
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let first = sortedNumbers[0]
let last = sortedNumbers[sortedNumbers.count - 1]
let middle = sortedNumbers[sortedNumbers.count / 2]
let distanceToFirst = abs(first - middle)
let distanceToLast = abs(last - middle)
if distanceToFirst < distanceToLast {
return (first, last)
} else {
return (last, first)
}
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func singleNumber(nums: [Int]) -> Int {
return nums.reduce(0, { acc, num in
acc ^ num
})
}
func singleNumber2(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
func singleNumber3(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = twos & ones
}
return ones
}
func singleNumber4(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = ones & twos
}
return ones
}
func singleNumber5(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = ones & twos
}
return ones
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sortedNumbers = numbers.sorted()
let first = sortedNumbers[0]
let last = sortedNumbers[sortedNumbers.count - 1]
let middle = sortedNumbers[sortedNumbers.count / 2]
let distanceToFirst = abs(first - middle)
let distanceToLast = abs(last - middle)
if distanceToFirst < distanceToLast {
return (first, last)
} else {
return (last, first)
}
}
// 2. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array of integers, every element appears twice except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,1]
// Output: 1
func singleNumber(nums: [Int]) -> Int {
return nums.reduce(0, { acc, num in
acc ^ num
})
}
// 4. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber2(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
// 5. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber3(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = twos & ones
}
return ones
}
// 6. Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber4(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = ones & twos
}
return ones
}
// 7. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber5(nums: [Int]) -> Int {
var ones = 0
var twos = 0
var threes = 0
for num in nums {
ones = (ones ^ num) & ~threes
twos = (twos ^ num) & ~ones
threes = ones & twos
}
return ones
}
// 8. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber6(
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
func removeVowels(input: String) -> String {
return input.filter { !"aeiouAEIOU".contains(Character($0)) }
}
func maxSubArray(numbers: [Double]) -> Double {
var max = numbers.first() ?? 0.0
var current = 0.0
for number in numbers {
current = max(current + number, number)
max = max(current, max)
}
return max
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// ----------------------------------------------------------------------------------------------------------------------
// Given a string, return a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
return input.filter { !"aeiouAEIOU".contains(Character($0)) }
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the largest sum of any contiguous subarray of the array.
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([-1, -2, -3, -4, -5]) == -1
func maxSubArray(numbers: [Double]) -> Double {
var max = numbers.first() ?? 0.0
var current = 0.0
for number in numbers {
current = max(current + number, number)
max = max(current, max)
}
return max
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the largest sum of any contiguous subarray of the array.
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([-1, -2, -3, -4, -5]) == -1
func maxSubArray(numbers: [Double]) -> Double {
var max = numbers.first() ?? 0.0
var current = 0.0
for number in numbers {
current = max(current + number, number)
max = max(current, max)
}
return max
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the largest sum of any contiguous subarray of the array.
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([-1, -2, -3, -4, -5]) == -1
func maxSubArray(numbers: [Double]) -> Double {
var max = numbers.first() ?? 0.0
var current = 0.0
for number in numbers {
current = max(current + number, number)
max = max(current, max)
}
return max
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the largest sum of any contiguous subarray of the array.
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([-1, -2, -3, -4, -5]) == -1
func maxSubArray(numbers: [Double]) -> Double {
var max = numbers.first() ?? 0.0
var current = 0.0
for number in numbers {
current = max(current + number, number)
max = max(current, max)
}
return max
}
// ------
return input.filter { !"aeiouAEIOU".contains(Character($0)) } // missing argument label 'extendedGraphemeClusterLiteral:' in call
var max = numbers.first() ?? 0.0 // cannot call value of non-function type 'Double?'
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / numbers.max() }
}
func rescaleToMean(numbers: [Double]) -> Double {
return numbers.reduce(0.0) { $0 + $1 } / numbers.count
}
func rescaleToMedian(numbers: [Double]) -> Double {
return numbers.sorted().median()
}
func rescaleToMode(numbers: [Double]) -> Double {
return numbers.mode()
}
func rescaleToRange(numbers: [Double]) -> Double {
return numbers.max() - numbers.min()
}
func rescaleToStandardDeviation(numbers: [Double]) -> Double {
return numbers.standardDeviation()
}
func rescaleToVariance(numbers: [Double]) -> Double {
return numbers.variance()
}
func rescaleToSkewness(numbers: [Double]) -> Double {
return numbers.skewness()
}
func rescaleToKurtosis(numbers: [Double]) -> Double {
return numbers.kurtosis()
}
func rescaleToEntropy(numbers: [Double]) -> Double {
return numbers.entropy()
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / numbers.max() }
}
// Given an array of numbers, return the mean
// rescaleToMean(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToMean(numbers: [Double]) -> Double {
return numbers.reduce(0.0) { $0 + $1 } / numbers.count
}
// Given an array of numbers, return the median
// rescaleToMedian(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToMedian(numbers: [Double]) -> Double {
return numbers.sorted().median()
}
// Given an array of numbers, return the mode
// rescaleToMode(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 2.0
func rescaleToMode(numbers: [Double]) -> Double {
return numbers.mode()
}
// Given an array of numbers, return the range
// rescaleToRange(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToRange(numbers: [Double]) -> Double {
return numbers.max() - numbers.min()
}
// Given an array of numbers, return the standard deviation
// rescaleToStandardDeviation(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 1.0
func rescaleToStandardDeviation(numbers: [Double]) -> Double {
return numbers.standardDeviation()
}
// Given an array of numbers, return the variance
// rescaleToVariance(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 1.0
func rescaleToVariance(numbers: [Double]) -> Double {
return numbers.variance()
}
// Given an array of numbers, return the skewness
// rescaleToSkewness(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToSkewness(numbers: [Double]) -> Double {
return numbers.skewness()
}
// Given an array of numbers, return the kurtosis
// rescaleToKurtosis(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToKurtosis(numbers: [Double]) -> Double {
return numbers.kurtosis()
}
// Given an array of numbers, return the entropy
// rescaleToEntropy(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToEntropy(numbers: [Double]) -> Double {
return numbers.entropy()
}
// Given an array of numbers, return the entropy
// rescaleToEntropy(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToEntropy(numbers: [Double]) -> Double {
return numbers.entropy()
}
// Given an array of numbers, return the entropy
// rescaleToEntropy(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToEntropy(numbers: [Double]) -> Double {
return numbers.entropy()
}
// Given an array of numbers, return the entropy
// rescaleToEntropy(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 0.0
func rescaleToEntropy(numbers: [Double]) -> Double {
return numbers.entropy()
}
// Given an array of numbers, return the entropy
// rescaleToEntropy(numbers: [1.0, 2.0, 3.0, 4.0, 5.
return numbers.map { $0 / numbers.max() } // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return numbers.reduce(0.0) { $0 + $1 } / numbers.count // cannot convert value of type 'Int' to expected argument type 'Double'
return numbers.sorted().median() // value of type '[Double]' has no member 'median'
return numbers.mode() // value of type '[Double]' has no member 'mode'
return numbers.max() - numbers.min() // binary operator '-' cannot be applied to two 'Double?' operands
return numbers.standardDeviation() // value of type '[Double]' has no member 'standardDeviation'
return numbers.variance() // value of type '[Double]' has no member 'variance'
return numbers.skewness() // value of type '[Double]' has no member 'skewness'
return numbers.kurtosis() // value of type '[Double]' has no member 'kurtosis'
return numbers.entropy() // value of type '[Double]' has no member 'entropy'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
let range = max - min
return numbers.map { $0 - min }.map { $0 / range }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min() ?? 0.0
let max = numbers.max() ?? 0.0
let range = max - min
return numbers.map { $0 - min }.map { $0 / range }
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return a new array with the same numbers, but with the numbers
// in reverse order.
// reverseArray([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
func reverseArray(numbers: [Double]) -> [Double] {
return numbers.reversed()
}
// Given an array of numbers, return
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
func rescaleToMean(numbers: [Double]) -> Double {
let sum = numbers.reduce(0.0, { $0 + $1 })
return sum / numbers.count
}
func rescaleToMedian(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let middle = sorted.count / 2
return sorted[middle]
}
func rescaleToMode(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })!
return mode
}
func rescaleToRange(numbers: [Double]) -> Double {
let min = numbers.min()!
let max = numbers.max()!
return max - min
}
func rescaleToStandardDeviation(numbers: [Double]) -> Double {
let mean = rescaleToMean(numbers: numbers)
let squaredDifferences = numbers.map { $0 - mean }.map { $0 * $0 }
let sumSquaredDifferences = squaredDifferences.reduce(0.0, { $0 + $1 })
return sqrt(sumSquaredDifferences / numbers.count)
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the mean (average) of the numbers
// rescaleToMean(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToMean(numbers: [Double]) -> Double {
let sum = numbers.reduce(0.0, { $0 + $1 })
return sum / numbers.count
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the median (middle number) of the numbers
// rescaleToMedian(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToMedian(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let middle = sorted.count / 2
return sorted[middle]
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the mode (most common number) of the numbers
// rescaleToMode(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 3.0
func rescaleToMode(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })!
return mode
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the range (difference between the smallest and largest number) of the numbers
// rescaleToRange(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 4.0
func rescaleToRange(numbers: [Double]) -> Double {
let min = numbers.min()!
let max = numbers.max()!
return max - min
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the standard deviation (average of the absolute differences from the mean) of the numbers
// rescaleToStandardDeviation(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 1.0
func rescaleToStandardDeviation(numbers: [Double]) -> Double {
let mean = rescaleToMean(numbers: numbers)
let squaredDifferences = numbers.map { $0 - mean }.map { $0 * $0 }
let sumSquaredDifferences = squaredDifferences.reduce(0.0, { $0 + $1 })
return sqrt(sumSquaredDifferences / numbers.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the variance (average of the squared differences from the mean) of the numbers
// rescaleToVariance(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == 1.0
func rescaleToVariance(numbers: [Double]) -> Double {
let mean = rescaleToMean(numbers: numbers)
let squaredDifferences = numbers.map { $0 - mean
return sum / numbers.count // cannot convert value of type 'Int' to expected argument type 'Double'
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })! // cannot call value of non-function type 'Int'
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })! // cannot call value of non-function type 'Int'
return sqrt(sumSquaredDifferences / numbers.count) // cannot convert value of type 'Int' to expected argument type 'Double'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: -
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }.map { $0 / (max - min) }
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 2.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { number in
(number - min) / range
}
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { number in
(number - min) / range
}
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 1.2.2.3.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { number in
(number - min) / range
}
}
func mean(numbers: [Double]) -> Double {
return numbers.reduce(0.0, { $0 + $1 }) / numbers.count
}
func median(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let middle = sorted.count / 2
return sorted[middle]
}
func mode(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })!
return mode
}
func range(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
return sorted.last()! - sorted.first()!
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let squaredDiffs = numbers.map { number in
(number - mean) * (number - mean)
}
let sum = squaredDiffs.reduce(0.0, { $0 + $1 })
return sqrt(sum / numbers.count)
}
func variance(numbers: [Double]) -> Double {
return standardDeviation(numbers: numbers) * standardDeviation(numbers: numbers)
}
func skewness(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let squaredDiffs = numbers.map { number in
(number - mean) * (number - mean)
}
let sum = squaredDiffs.reduce(0.0, { $0 + $1 })
return sum / numbers.count
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { number in
(number - min) / range
}
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the mean
// mean([1, 2, 3, 4, 5]) == 3.0
func mean(numbers: [Double]) -> Double {
return numbers.reduce(0.0, { $0 + $1 }) / numbers.count
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the median
// median([1, 2, 3, 4, 5]) == 3.0
func median(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let middle = sorted.count / 2
return sorted[middle]
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the mode
// mode([1, 2, 3, 4, 5]) == 1.0
func mode(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })!
return mode
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the range
// range([1, 2, 3, 4, 5]) == 4.0
func range(numbers: [Double]) -> Double {
let sorted = numbers.sorted()
return sorted.last()! - sorted.first()!
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the standard deviation
// standardDeviation([1, 2, 3, 4, 5]) == 1.0
func standardDeviation(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let squaredDiffs = numbers.map { number in
(number - mean) * (number - mean)
}
let sum = squaredDiffs.reduce(0.0, { $0 + $1 })
return sqrt(sum / numbers.count)
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the variance
// variance([1, 2, 3, 4, 5]) == 1.0
func variance(numbers: [Double]) -> Double {
return standardDeviation(numbers: numbers) * standardDeviation(numbers: numbers)
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array of numbers, return the skewness
// skewness([1, 2, 3, 4, 5]) == 0.0
func skewness(numbers: [Double]) -> Double {
let mean = mean(numbers: numbers)
let squaredDiffs = numbers.map { number in
(number - mean) * (number - mean)
}
let sum = squaredDiffs.reduce(0.0, { $0 + $1 })
return sum / numbers.count
}
// ---------------------------------------------------------------------
return numbers.reduce(0.0, { $0 + $1 }) / numbers.count // cannot convert value of type 'Int' to expected argument type 'Double'
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })! // cannot call value of non-function type 'Int'
let mode = sorted.first(where: { sorted.count(for: $0) == sorted.count(for: $0) })! // cannot call value of non-function type 'Int'
return sorted.last()! - sorted.first()! // cannot call value of non-function type 'Double?'
return sorted.last()! - sorted.first()! // cannot call value of non-function type 'Double?'
return sqrt(sum / numbers.count) // cannot convert value of type 'Int' to expected argument type 'Double'
return sum / numbers.count // cannot convert value of type 'Int' to expected argument type 'Double'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0 as! NSNumber) {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0 as! NSNumber) {
return true
} else {
return false
}
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case .number(of: Int.self):
return true
default:
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case .number(of: Int.self):
return true
default:
return false
}
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
case .number(of: Int.self): // type 'Int.Type' cannot conform to '_ErrorCodeProtocol'
case .number(of: Int.self): // type 'AnyHashable' has no member 'number'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case let i as Int:
return true
default:
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case let i as Int:
return true
default:
return false
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try? $0 as! NSNumber) {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try? $0 as! NSNumber) {
return true
} else {
return false
}
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string and returns a new string with all vowels removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns a new string with all non-alphabetic characters removed.
// ---------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
if let int = Int(try? $0 as! NSNumber) { // value of optional type 'NSNumber?' not unwrapped; did you mean to use 'try!' or chain with '?'?
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let int = Int(try! $0) {
return int
} else {
return nil
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let int = Int(try! $0) {
return int
} else {
return nil
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if let int = Int(try! $0) { // cannot convert value of type 'AnyHashable' to expected argument type 'String'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0) {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0) {
return true
} else {
return false
}
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
if let int = Int(try! $0) { // cannot convert value of type 'AnyHashable' to expected argument type 'String'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case let n as Int:
return true
default:
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
switch $0 {
case let n as Int:
return true
default:
return false
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0 as! NSNumber) {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try! $0 as! NSNumber) {
return true
} else {
return false
}
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try? $0.description) {
return true
} else {
return false
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
if let int = Int(try? $0.description) {
return true
} else {
return false
}
}
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string and returns a string with the first letter capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 18. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
return values.filter { // cannot convert return expression of type '[AnyHashable]' to return type '[Int]'
if let int = Int(try? $0.description) { // value of optional type 'String?' not unwrapped; did you mean to use 'try!' or chain with '?'?
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
let value = $0 as? Int
return value != nil
} as! [Int]
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter {
let value = $0 as? Int
return value != nil
} as! [Int]
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func strlen(string: String) -> Int {
return string.count
}
func isEmpty(string: String) -> Bool {
return string.isEmpty
}
func isNotEmpty(string: String) -> Bool {
return !string.isEmpty
}
func isWhitespace(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty
}
func isNotWhitespace(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty
}
func isEmptyOrWhitespace(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty
}
func isNotEmptyOrWhitespace(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty
}
func isEmptyOrWhitespaceOrEmpty(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty || string.isEmpty
}
func isNotEmptyOrWhitespaceOrEmpty(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty || string.isEmpty
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// Return true if given string is empty
// strlen(string: "") == true
// strlen(string: "abc") == false
func isEmpty(string: String) -> Bool {
return string.isEmpty
}
// Return true if given string is not empty
// strlen(string: "") == false
// strlen(string: "abc") == true
func isNotEmpty(string: String) -> Bool {
return !string.isEmpty
}
// Return true if given string is empty or contains only whitespace characters
// strlen(string: "") == true
// strlen(string: " ") == true
// strlen(string: " ") == true
// strlen(string: " a ") == true
// strlen(string: " a b ") == true
// strlen(string: " a b ") == false
func isWhitespace(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty
}
// Return true if given string is not empty or contains only whitespace characters
// strlen(string: "") == false
// strlen(string: " ") == false
// strlen(string: " ") == false
// strlen(string: " a ") == false
// strlen(string: " a b ") == false
// strlen(string: " a b ") == true
func isNotWhitespace(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty
}
// Return true if given string is empty or contains only whitespace characters
// strlen(string: "") == true
// strlen(string: " ") == true
// strlen(string: " ") == true
// strlen(string: " a ") == true
// strlen(string: " a b ") == true
// strlen(string: " a b ") == false
func isEmptyOrWhitespace(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty
}
// Return true if given string is not empty or contains only whitespace characters
// strlen(string: "") == false
// strlen(string: " ") == false
// strlen(string: " ") == false
// strlen(string: " a ") == false
// strlen(string: " a b ") == false
// strlen(string: " a b ") == true
func isNotEmptyOrWhitespace(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty
}
// Return true if given string is empty or contains only whitespace characters
// strlen(string: "") == true
// strlen(string: " ") == true
// strlen(string: " ") == true
// strlen(string: " a ") == true
// strlen(string: " a b ") == true
// strlen(string: " a b ") == false
func isEmptyOrWhitespaceOrEmpty(string: String) -> Bool {
return string.isEmpty || string.trim().isEmpty || string.isEmpty
}
// Return true if given string is not empty or contains only whitespace characters
// strlen(string: "") == false
// strlen(string: " ") == false
// strlen(string: " ") == false
// strlen(string: " a ") == false
// strlen(string: " a b ") == false
// strlen(string: " a b ") == true
func isNotEmptyOrWhitespaceOrEmpty(string: String) -> Bool {
return !string.isEmpty && !string.trim().isEmpty || string.isEmpty
}
// Return true if given string is empty or contains only whitespace characters
// strlen(string: "") == true
// strlen(string: " ") == true
// strlen(string: " ") == true
// strlen(string: " a ") == true
// strlen(string: " a b ") == true
// strlen(string: " a b ") == false
func isEmptyOrWhitespaceOrEmptyOrEmpty(string: String) -> Bool {
return
return string.isEmpty || string.trim().isEmpty // value of type 'String' has no member 'trim'
return !string.isEmpty && !string.trim().isEmpty // value of type 'String' has no member 'trim'
return string.isEmpty || string.trim().isEmpty // value of type 'String' has no member 'trim'
return !string.isEmpty && !string.trim().isEmpty // value of type 'String' has no member 'trim'
return string.isEmpty || string.trim().isEmpty || string.isEmpty // value of type 'String' has no member 'trim'
return !string.isEmpty && !string.trim().isEmpty || string.isEmpty // value of type 'String' has no member 'trim'
func strlen(string: String) -> Int {
return string.count
}
func strchr(string: String, c: Character) -> String {
return string.first(where: { $0 == c }) ?? ""
}
func strrchr(string: String, c: Character) -> String {
return string.last(where: { $0 == c }) ?? ""
}
func strstr(string: String, substring: String) -> String {
return string.first(where: { substring.contains($0) }) ?? ""
}
func strrstr(string: String, substring: String) -> String {
return string.last(where: { substring.contains($0) }) ?? ""
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// Return the first character of the given string
// strchr(string: "", c: 'a') == ""
// strchr(string: "abc", c: 'a') == "a"
func strchr(string: String, c: Character) -> String {
return string.first(where: { $0 == c }) ?? ""
}
// Return the last character of the given string
// strrchr(string: "", c: 'a') == ""
// strrchr(string: "abc", c: 'a') == "a"
func strrchr(string: String, c: Character) -> String {
return string.last(where: { $0 == c }) ?? ""
}
// Return the first occurrence of the given character in the given string
// strchr(string: "", c: 'a') == ""
// strchr(string: "abc", c: 'a') == "a"
// strchr(string: "abc", c: 'b') == "b"
// strchr(string: "abc", c: 'c') == "c"
// strchr(string: "abc", c: 'd') == ""
func strchr(string: String, c: Character) -> String {
return string.first(where: { $0 == c }) ?? ""
}
// Return the last occurrence of the given character in the given string
// strrchr(string: "", c: 'a') == ""
// strrchr(string: "abc", c: 'a') == "a"
// strrchr(string: "abc", c: 'b') == "b"
// strrchr(string: "abc", c: 'c') == "c"
// strrchr(string: "abc", c: 'd') == ""
func strrchr(string: String, c: Character) -> String {
return string.last(where: { $0 == c }) ?? ""
}
// Return the first occurrence of the given substring in the given string
// strstr(string: "", substring: "") == ""
// strstr(string: "abc", substring: "") == "abc"
// strstr(string: "abc", substring: "a") == "a"
// strstr(string: "abc", substring: "b") == "b"
// strstr(string: "abc", substring: "c") == "c"
// strstr(string: "abc", substring: "d") == ""
func strstr(string: String, substring: String) -> String {
return string.first(where: { substring.contains($0) }) ?? ""
}
// Return the last occurrence of the given substring in the given string
// strrstr(string: "", substring: "") == ""
// strrstr(string: "abc", substring: "") == "abc"
// strrstr(string: "abc", substring: "a") == "a"
// strrstr(string: "abc", substring: "b") == "b"
// strrstr(string: "abc", substring: "c") == "c"
// strrstr(string: "abc", substring: "d") == ""
func strrstr(string: String, substring: String) -> String {
return string.last(where: { substring.contains($0) }) ?? ""
}
// Return the first occurrence of the given character in the given string
// strchr(string: "", c: 'a') == ""
// strchr(string: "abc", c: 'a') == "a"
// strchr(string: "abc", c: 'b') == "b"
// strchr(string: "abc", c: 'c') == "c"
// strchr(string: "abc", c: 'd') == ""
func strchr(string: String, c: Character) -> String {
return string.first(where: { $0 == c }) ?? ""
}
// Return the last
return string.first(where: { $0 == c }) ?? "" // binary operator '??' cannot be applied to operands of type 'String.Element?' (aka 'Optional<Character>') and 'String'
return string.first(where: { $0 == c }) ?? "" // no '??' candidates produce the expected contextual result type 'String'
return string.last(where: { $0 == c }) ?? "" // binary operator '??' cannot be applied to operands of type 'String.Element?' (aka 'Optional<Character>') and 'String'
return string.last(where: { $0 == c }) ?? "" // no '??' candidates produce the expected contextual result type 'String'
return string.first(where: { substring.contains($0) }) ?? "" // no '??' candidates produce the expected contextual result type 'String'
return string.first(where: { substring.contains($0) }) ?? "" // binary operator '??' cannot be applied to operands of type 'String.Element?' (aka 'Optional<Character>') and 'String'
return string.last(where: { substring.contains($0) }) ?? "" // binary operator '??' cannot be applied to operands of type 'String.Element?' (aka 'Optional<Character>') and 'String'
return string.last(where: { substring.contains($0) }) ?? "" // no '??' candidates produce the expected contextual result type 'String'
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// 1.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
func strlen(string: String) -> Int {
return string.count
}
func firstChar(string: String) -> String {
return string.first!
}
func lastChar(string: String) {
return string.last!
}
func substring(string: String, start: Int, length: Int) -> String {
return string.substring(start: start, length: length)
}
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// Return the first character of a string
// firstChar("abc") == "a"
func firstChar(string: String) -> String {
return string.first!
}
// Return the last character of a string
// lastChar("abc") == "c"
func lastChar(string: String) {
return string.last!
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int, length: Int) -> String {
return string.substring(start: start, length: length)
}
// Return the substring of a string
// substring("abc", 1) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int, length: Int) -> String {
return string.substring(start: start, length: length)
}
// Return the substring of a string
// substring("abc", 1) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.substring(start: start)
}
// Return the substring of a string
// substring("abc", 1, 2) == "bc"
func substring(string: String, start: Int) -> String {
return string.
return string.first! // cannot convert return expression of type 'String.Element' (aka 'Character') to return type 'String'
return string.last! // unexpected non-void return value in void function
return string.substring(start: start, length: length) // no exact matches in call to instance method 'substring'
return string.substring(start: start) // no exact matches in call to instance method 'substring'
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string: "abc") == "cba"
// strrev(string: "abcdef") == "fedcba"
//
// Note: You can use the built-in `reverse` function, but don't use it.
//
// Hint: You can use the `for` loop to iterate over the string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string: "abc") == "cba"
// strrev(string: "abcdef") == "fedcba"
//
// Note: You can use the built-in `reverse` function, but don't use it.
//
// Hint: You can use the `for` loop to iterate over the string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string: "abc") == "cba"
// strrev(string: "abcdef") == "fedcba"
//
// Note: You can use the built-in `reverse` function, but don't use it.
//
// Hint: You can use the `for` loop to iterate over the string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string: "abc") == "cba"
// strrev(string: "abcdef") == "fedcba"
//
// Note: You can use the built-in `reverse` function, but don't use it.
//
// Hint: You can use the `for` loop to iterate over the string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string: "abc") == "cba"
// strrev(string: "abcdef") == "fedcba"
//
// Note: You can use the built-in `reverse` function, but don't use it.
//
// Hint: You can use the `for` loop to iterate over the string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all
// characters in reverse order.
//
// strrev(string: "") == ""
// strrev(string
func strlen(string: String) -> Int {
return string.count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// 1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [1]
for i in 1...nums.count {
result.append(result[i - 1] * nums[i - 1])
}
var right = 1
for i in (nums.count - 1...1).reversed {
result[i] = result[i] * right
right *= nums[i]
}
return result
}
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// productExceptSelf(nums: [1, 2, 3, 4]) == [24, 12, 8, 6]
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [1]
for i in 1...nums.count {
result.append(result[i - 1] * nums[i - 1])
}
var right = 1
for i in (nums.count - 1...1).reversed {
result[i] = result[i] * right
right *= nums[i]
}
return result
}
// 4. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
// 5. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
// 6. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
// 7. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
// 8. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.count * (nums.count + 1) / 2) - sum
}
// 9. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num
}
return (nums.
for i in (1...n).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
for i in (nums.count - 1...1).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func numberOf1Bits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// The 32-bit integer 11 has binary representation
// 00000000000000000000000000001111
// so the function should return 3.
func numberOf1Bits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001111
// so the function should return 3.
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001111
// so the function should return 3.
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation
// 00000000000000000000000000001111
// so the function should return 3.
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’
for i in (1...n).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
count += n & 1 // cannot convert value of type 'UInt' to expected argument type 'Int'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in (2...n) {
if n % i == 0 {
return false
}
}
return true
}
func sumTo(n: Int) -> Int {
var sum = 0
for i in (0...n) {
sum += i
}
return sum
}
func factorial(n: Int) -> Int {
var result = 1
for i in (1...n) {
result *= i
}
return result
}
func factorial(n: Int) -> [Int] {
var result = [1]
for i in (1...n) {
result.append(result[i - 1] * i)
}
return result
}
func fibonacci(n: Int) -> [Int] {
var result = [1, 1]
for i in (2...n) {
result.append(result[i - 1] + result[i - 2])
}
return result
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a number as an argument and returns a Boolean
// indicating whether the number is a prime number.
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in (2...n) {
if n % i == 0 {
return false
}
}
return true
}
// 3. Write a function that takes a number as an argument and returns the
// sum of all numbers from 0 to the number.
// sumTo(n: 10) == 55
func sumTo(n: Int) -> Int {
var sum = 0
for i in (0...n) {
sum += i
}
return sum
}
// 4. Write a function that takes a number as an argument and returns the
// factorial of that number.
// factorial(n: 5) == 120
func factorial(n: Int) -> Int {
var result = 1
for i in (1...n) {
result *= i
}
return result
}
// 5. Write a function that takes a number as an argument and returns the
// factorial of the first n numbers.
// factorial(n: 5) == [1, 1, 2, 6, 24]
func factorial(n: Int) -> [Int] {
var result = [1]
for i in (1...n) {
result.append(result[i - 1] * i)
}
return result
}
// 6. Write a function that takes a number as an argument and returns the
// Fibonacci sequence up to that number.
// fibonacci(n: 5) == [1, 1, 2, 3, 5]
func fibonacci(n: Int) -> [Int] {
var result = [1, 1]
for i in (2...n) {
result.append(result[i - 1] + result[i - 2])
}
return result
}
// 7. Write a function that takes a number as an argument and returns the
// Fibonacci sequence up to the nth number.
// fibonacci(n: 5) == [1, 1, 2, 3, 5]
func fibonacci(n: Int) -> [Int] {
var result = [1, 1]
for i in (2...n) {
result.append(result[i - 1] + result[i - 2])
}
return result
}
// 8. Write a function that takes a number as an argument and returns the
// Fibonacci sequence up to the nth number.
// fibonacci(n: 5) == [1, 1, 2, 3, 5]
func fibonacci(n: Int) -> [Int] {
var result = [1, 1]
for i in (2...n) {
result.append(result[i - 1] + result[i - 2])
}
return result
}
// 9. Write a function that takes a number as an argument and returns the
// Fibonacci sequence up to the nth number.
// fibonacci(n: 5) == [1, 1, 2, 3, 5]
func fibonacci(n: Int) -> [Int] {
var result = [1, 1]
for i in (2...n) {
result.append(result[i - 1] + result[i - 2])
}
return result
}
// 10. Write a function that takes a number as an argument and returns the
// Fibonacci sequence up to the nth number.
// fibonacci(n: 5) == [1, 1, 2, 3, 5]
for i in (1...n).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func stringFromNumber(number: Int) -> String {
return String(number)
}
func stringLength(string: String) -> Int {
return string.count
}
func numberOfVowels(string: String) -> Int {
return string.count(..., where: \Character.isVowel)
}
func numberOfConsonants(string: String) -> Int {
return string.count(..., where: \Character.isConsonant)
}
func numberOfUpperCaseLetters(string: String) -> Int {
return string.count(..., where: \Character.isUpperCase)
}
func numberOfLowerCaseLetters(string: String) -> Int {
return string.count(..., where: \Character.isLowercase)
}
func numberOfDigits(string: String) -> Int {
return string.count(..., where: \Character.isDigit)
}
func numberOfWords(string: String) -> Int {
return string.split(..., options: .trimLeading | .trimTrailing).count
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
// 11. Write a function that takes a string as parameter and returns a new string that
// contains all the characters of the input string in reverse order.
// reverseString("Hello") == "olleH"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 12. Write a function that takes a number as parameter and returns a new string that
// contains the number as a string.
// stringFromNumber(123) == "123"
func stringFromNumber(number: Int) -> String {
return String(number)
}
// 13. Write a function that takes a string as parameter and returns the number of
// characters in the string.
// stringLength("Hello") == 5
func stringLength(string: String) -> Int {
return string.count
}
// 14. Write a function that takes a string as parameter and returns the number of
// vowels in the string.
// numberOfVowels("Hello") == 2
func numberOfVowels(string: String) -> Int {
return string.count(..., where: \Character.isVowel)
}
// 15. Write a function that takes a string as parameter and returns the number of
// consonants in the string.
// numberOfConsonants("Hello") == 3
func numberOfConsonants(string: String) -> Int {
return string.count(..., where: \Character.isConsonant)
}
// 16. Write a function that takes a string as parameter and returns the number of
// uppercase letters in the string.
// numberOfUpperCaseLetters("Hello") == 1
func numberOfUpperCaseLetters(string: String) -> Int {
return string.count(..., where: \Character.isUpperCase)
}
// 17. Write a function that takes a string as parameter and returns the number of
// lowercase letters in the string.
// numberOfLowerCaseLetters("Hello") == 5
func numberOfLowerCaseLetters(string: String) -> Int {
return string.count(..., where: \Character.isLowercase)
}
// 18. Write a function that takes a string as parameter and returns the number of
// digits in the string.
// numberOfDigits("Hello") == 0
func numberOfDigits(string: String) -> Int {
return string.count(..., where: \Character.isDigit)
}
// 19. Write a function that takes a string as parameter and returns the number of
// words in the string.
// numberOfWords("Hello world") == 2
func numberOfWords(string: String) -> Int {
return string.split(..., options: .trimLeading | .trimTrailing).count
}
// 20. Write a function that takes a string as parameter and returns the number of
// words in the string.
// numberOfWords("Hello world") == 2
func numberOfWords(string: String) -> Int {
return string.split(..., options: .trimLeading | .trimTrailing).count
}
// 21. Write a function that takes a string as parameter and returns the number of
// words in the string.
// numberOfWords("Hello world") == 2
func numberOfWords(string: String) -> Int {
return string.split(..., options: .trimLeading | .trimTrailing).count
}
// 22. Write a function that takes a string as parameter and returns the number of
// words in the string.
// numberOfWords("Hello world") == 2
func numberOfWords(string: String) -> Int {
return string.split(..., options: .trimLeading | .trimTrailing).count
}
// 23. Write a function that takes a string as parameter and returns the number of
// words in the string.
// numberOfWords(
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string.count(..., where: \Character.isVowel) // value of type 'Character' has no member 'isVowel'
return string.count(..., where: \Character.isVowel) // cannot call value of non-function type 'Int'
return string.count(..., where: \Character.isConsonant) // cannot call value of non-function type 'Int'
return string.count(..., where: \Character.isConsonant) // value of type 'Character' has no member 'isConsonant'
return string.count(..., where: \Character.isUpperCase) // cannot call value of non-function type 'Int'
return string.count(..., where: \Character.isUpperCase) // value of type 'Character' has no member 'isUpperCase'
return string.count(..., where: \Character.isLowercase) // cannot call value of non-function type 'Int'
return string.count(..., where: \Character.isDigit) // value of type 'Character' has no member 'isDigit'
return string.count(..., where: \Character.isDigit) // cannot call value of non-function type 'Int'
return string.split(..., options: .trimLeading | .trimTrailing).count // no exact matches in call to instance method 'split'
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
// 10. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 11. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 12. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 13. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 14. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 15. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return result
}
// 16. Write a function that takes a number as an argument, and returns a new number where the digits of the new number are all the same as the original number.
// zeroPad(n: 100) == 100
// zeroPad(n: 1234) == 1234
func zeroPad(n: Int) -> Int {
var result = 0
var i = 1
while n > 0 {
result = result * 10 + n % 10
n /= 10
}
return
n /= 10 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// Example:
// Input: [1,2,3,4]
// Output: [24,12,8,6]
// Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
// Note: Please solve it without division and in O(n).
// Follow up:
// Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
// 4. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// 5. Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
// Example:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// 6. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 7. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 8. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 9. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 10. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 11. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// 12. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 10
for i in (1...n).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [1]
for i in 1...nums.count {
result.append(result[i-1] * nums[i-1])
}
var right = 1
for i in (nums.count-1...0) {
result[i] = result[i] * right
right *= nums[i]
}
return result
}
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
func missingNumber2(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
func missingNumber3(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
func missingNumber4(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
func missingNumber5(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
func missingNumber6(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// productExceptSelf(nums: [1, 2, 3, 4]) == [24, 12, 8, 6]
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [1]
for i in 1...nums.count {
result.append(result[i-1] * nums[i-1])
}
var right = 1
for i in (nums.count-1...0) {
result[i] = result[i] * right
right *= nums[i]
}
return result
}
// 4. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber(nums: [3, 0, 1]) == 2
func missingNumber(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 5. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber2(nums: [3, 0, 1]) == 2
func missingNumber2(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 6. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber3(nums: [3, 0, 1]) == 2
func missingNumber3(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 7. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber4(nums: [3, 0, 1]) == 2
func missingNumber4(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 8. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber5(nums: [3, 0, 1]) == 2
func missingNumber5(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 9. Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
// missingNumber6(nums: [3, 0, 1]) == 2
func missingNumber6(nums: [Int]) -> Int {
var sum = 0
for i in nums {
sum += i
}
return (1...nums.count).sum() - sum
}
// 10. Given an array nums containing n distinct numbers
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
return (1...nums.count).sum() - sum // value of type 'ClosedRange<Int>' has no member 'sum'
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
// 12. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 13. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 14. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 15. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 16. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 17. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 18. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 19. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 20. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n).filter(Character.isOne).count
}
// 21. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
return String(n
return String(n).filter(Character.isOne).count // type 'Character' has no member 'isOne'
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n) {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 4. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 5. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 6. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 7. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 8. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
func findNumbers(nums: [Int]) -> Int {
var count = 0
for num in nums {
if String(num).count % 2 == 0 {
count += 1
}
}
return count
}
// 9. Given an array nums of integers, return how many of them contain an even number of digits.
// findNumbers([12,345,2,6,7896]) == 2
// findNumbers([555,901,482,1771]) == 1
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func isIsomorphic(s: String, t: String) -> Bool {
var sDict = [Character: Character]()
var tDict = [Character: Character]()
for i in 0..<s.count {
if sDict[s[i]] == nil {
sDict[s[i]] = t[i]
} else if sDict[s[i]] != t[i] {
return false
}
if tDict[t[i]] == nil {
tDict[t[i]] = s[i]
} else if tDict[t[i]] != s[i] {
return false
}
}
return true
}
func firstUniqChar(s: String) -> Int {
var sDict = [Character: Int]()
for i in 0..<s.count {
if sDict[s[i]] == nil {
sDict[s[i]] = i
} else {
sDict[s[i]] = -1
}
}
var minIndex = Int.max
for (key, value) in sDict {
if value != -1 && value < minIndex {
minIndex = value
}
}
return minIndex == Int.max ? -1 : minIndex
}
func longestPalindrome(s: String) -> String {
var maxLength = 0
var maxString = ""
for i in 0..<s.count {
for j in i..<s.count {
var subString = s[i..<j]
if subString.length == j - i + 1 && subString == subString.reversed() {
if subString.length > maxLength {
maxLength = subString.length
maxString = subString
}
}
}
}
return maxString
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
for i in (1...n).reversed {
if n % i == 0 {
return i
}
}
return 1
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given two strings s and t, determine if they are isomorphic.
// Two strings s and t are isomorphic if the characters in s can be replaced to get t.
// All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
// isIsomorphic(s: "egg", t: "add") == true
// isIsomorphic(s: "foo", t: "bar") == false
// isIsomorphic(s: "paper", t: "title") == true
func isIsomorphic(s: String, t: String) -> Bool {
var sDict = [Character: Character]()
var tDict = [Character: Character]()
for i in 0..<s.count {
if sDict[s[i]] == nil {
sDict[s[i]] = t[i]
} else if sDict[s[i]] != t[i] {
return false
}
if tDict[t[i]] == nil {
tDict[t[i]] = s[i]
} else if tDict[t[i]] != s[i] {
return false
}
}
return true
}
// 4. Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var sDict = [Character: Int]()
for i in 0..<s.count {
if sDict[s[i]] == nil {
sDict[s[i]] = i
} else {
sDict[s[i]] = -1
}
}
var minIndex = Int.max
for (key, value) in sDict {
if value != -1 && value < minIndex {
minIndex = value
}
}
return minIndex == Int.max ? -1 : minIndex
}
// 5. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var maxLength = 0
var maxString = ""
for i in 0..<s.count {
for j in i..<s.count {
var subString = s[i..<j]
if subString.length == j - i + 1 && subString == subString.reversed() {
if subString.length > maxLength {
maxLength = subString.length
maxString = subString
}
}
}
}
return maxString
}
// 6. Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var maxLength = 0
var maxString = ""
for i in 0..<s.count {
for j in i..<s.count {
var subString = s[i..<j]
if subString.length == j - i + 1 && subString == subString.reversed() {
for i in (1...n).reversed { // no 'reversed' overloads produce result type that conforms to 'Sequence'
if sDict[s[i]] == nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sDict[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sDict[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if sDict[s[i]] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if sDict[s[i]] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if tDict[t[i]] == nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
tDict[t[i]] = s[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
tDict[t[i]] = s[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if tDict[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if tDict[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if sDict[s[i]] == nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sDict[s[i]] = i // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sDict[s[i]] = -1 // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
for (key, value) in sDict { // immutable value 'key' was never used; consider replacing with '_' or removing it
var subString = s[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if subString.length == j - i + 1 && subString == subString.reversed() { // value of type 'String' has no member 'length'
if subString.length == j - i + 1 && subString == subString.reversed() { // cannot convert value of type 'ReversedCollection<String>' to expected argument type 'String'
if subString.length > maxLength { // value of type 'String' has no member 'length'
maxLength = subString.length // value of type 'String' has no member 'length'
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
// 2.
// Write a function that takes a string and returns a new string with all vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
// 3.
// Write a function that takes a string and returns a new string with all the vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
// 4.
// Write a function that takes a string and returns a new string with all the vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
// 5.
// Write a function that takes a string and returns a new string with all the vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
// 6.
// Write a function that takes a string and returns a new string with all the vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
// 7.
// Write a function that takes a string and returns a new string with all the vowels removed.
// The function should be case-insensitive, so "Um..." should return "m...".
// removeVowels("Um...") == "m..."
// removeVowels("Hello, world!") == "Hll, wrld!"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char.isVowel() {
continue
}
result += char
}
return result
}
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
if char.isVowel() { // value of type 'Character' has no member 'isVowel'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while n > 1 {
while n % i == 0 {
factors.append(i)
n /= i
}
i += 1
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while n > 1 {
while n % i == 0 {
factors.append(i)
n /= i
}
i += 1
}
return factors
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
if n > 1 {
factors.append(n)
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i * i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
if n > 1 {
factors.append(n)
}
return factors
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all vowels removed.
// Input: "Hello, world!"
// Output: "Hll, wrld!"
// Input: "aeiou"
// Output: ""
// Input: ""
// Output: ""
// Input: "a"
// Output: ""
// Input: "A"
// Output: ""
// Input: "Ae"
// Output: ""
// Input: "aeiouAEIOU"
// Output: ""
// Input: "aeiouAEIOU12345"
// Output: "12345"
// Input: "aeiouAEIOU12345!@#$%^&*()"
// Output: "12345!@#$%^&*()"
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()"
// Output: ""
// Input: "aeiouAEIOU12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!@#$%^&*()12345!
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 2. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 3. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 4. Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Example 1:
// Input: "A man, a plan, a canal: Panama"
// Output: true
// Example 2:
// Input: "race a car"
// Output: false
// ----------------------------------------------------------------------------------------------------------------------
// 5. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 6. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 7. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution,
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while n > 1 {
while n % i == 0 {
result.append(i)
n /= i
}
i += 1
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while n > 1 {
while n % i == 0 {
result.append(i)
n /= i
}
i += 1
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i <= n {
if n % i == 0 {
result.append(i)
n /= i
} else {
i += 1
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all vowels removed.
// Input: "Hello World"
// Output: "Hll Wrld"
// Input: "Hello World!"
// Output: "Hll Wrld!"
// Input: "Hello World!!!"
// Output: "Hll Wrld!!!"
// Input: "Hello World!!!!"
// Output: "Hll Wrld!!!!"
// Input: "Hello World!!!!!"
// Output: "Hll Wrld!!!!!"
// Input: "Hello World!!!!!!"
// Output: "Hll Wrld!!!!!!"
// Input: "Hello World!!!!!!!"
// Output: "Hll Wrld!!!!!!!"
// Input: "Hello World!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!"
// Input: "Hello World!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!!!!!"
// Output: "Hll Wrld!!!!!!!!!!!!!!!!!!!!!"
// Input: "Hello World!!!!!!!!!!!!!!!!!!!!!!
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1
// Given two strings, write a method to decide if one is a permutation of the other.
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation("abcd", "dabc") == true
// permutation(
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("I love apples!") == " lv pls!"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ------------------
if !isVowel(char: char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
func vowelFree(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.1
// -----------------------------------------------------------------------------
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello, world!") == "Hllwlr!"
func vowelFree(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.2
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.3
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.4
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.5
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.6
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String) -> Int {
var result = 0
for char in string {
result += 1
}
return result
}
// -----------------------------------------------------------------------------
// 1.2.7
// -----------------------------------------------------------------------------
// Given a string, return the number of times the character appears in the string.
// charCount("Hello, world!") == 3
func charCount(string: String)
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
for char in string { // immutable value 'char' was never used; consider replacing with '_' or removing it
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int]()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.append(number)
}
}
return result
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int]()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.append(number)
}
}
return result
}
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 5. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 6. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 7. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 8. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 9. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 10. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I love cats") == "l vcts"
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// 11. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// vowels removed.
// removeVowels("I am a string") == " m strng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
var result = ""
for char in input {
if char != "S" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns a new string with all
// the "S" characters removed.
// removeS("String") == "Trng"
func removeS(input: String) -> String {
if !isVowel(char: char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var last = 0
for n in numbers {
if n != last {
result.append(n)
last = n
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var last = 0
for n in numbers {
if n != last {
result.append(n)
last = n
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int]()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = [Int]()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if !result.contains(number) {
result.append(number)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func flipCase(string: String) -> String {
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'Array<_>' has no member 'join'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toUpperCase'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toLowerCase'
func flipCase(string: String) -> String {
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'Array<_>' has no member 'join'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toUpperCase'
return string.map { $0.isUpperCase() ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toLowerCase'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
return $0.uppercaseString // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercase
} else {
return $0.lowercase
}
}
}
func countVowels(string: String) -> Int {
return string.count(.vowel)
}
func isPalindrome(string: String) -> Bool {
return string.reversed == string
}
func doubleChar(string: String) -> String {
return string.map { $0 * 2 }
}
func swapFirstLast(string: String) -> String {
return string.last + string.substring(1, string.count - 2) + string.first
}
func removeVowels(string: String) -> String {
return string.remove(.vowel)
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercase
} else {
return $0.lowercase
}
}
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels(string: "Celebration") == 5
// countVowels(string: "Palm") == 1
func countVowels(string: String) -> Int {
return string.count(.vowel)
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome(string: "topot") == true
// isPalindrome(string: "Alibi") == true
// isPalindrome(string: "Racecar") == true
// isPalindrome(string: "Greetings") == false
func isPalindrome(string: String) -> Bool {
return string.reversed == string
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a string in which each character is repeated once.
// doubleChar(string: "String") == "SSttrriinngg"
// doubleChar(string: "Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar(string: "1234!_ ") == "11223344!!__ "
func doubleChar(string: String) -> String {
return string.map { $0 * 2 }
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapFirstLast(string: "Hello") == "oellH"
// swapFirstLast(string: "a") == "a"
// swapFirstLast(string: "abcdef") == "bcfedag"
func swapFirstLast(string: String) -> String {
return string.last + string.substring(1, string.count - 2) + string.first
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(string: "We're gonna build a wall!") == "W'r gnyb bld wll!"
// removeVowels(string: "Happy Thanksgiving!") == "Hppy Thnksgvny!"
func removeVowels(string: String) -> String {
return string.remove(.vowel)
}
// ----------------------------------------------------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapFirstLast(string: "Hello") == "oellH"
// swapFirstLast(string: "a") == "a"
// swapFirstLast(string: "abcdef") == "bcfedag"
func
return string.map { // cannot convert return expression of type '[T]' to return type 'String'
return $0.uppercase // value of type 'String.Element' (aka 'Character') has no member 'uppercase'
return string.count(.vowel) // cannot infer contextual base in reference to member 'vowel'
return string.count(.vowel) // cannot call value of non-function type 'Int'
return string.reversed == string // type '() -> [String.Element]' (aka '() -> Array<Character>') cannot conform to 'StringProtocol'
return string.map { $0 * 2 } // binary operator '*' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'Int'
return string.map { $0 * 2 } // no 'map' candidates produce the expected contextual result type 'String'
return string.last + string.substring(1, string.count - 2) + string.first // cannot convert value of type 'String.Element?' (aka 'Optional<Character>') to expected argument type 'String'
return string.last + string.substring(1, string.count - 2) + string.first // cannot convert value of type 'String.Element?' (aka 'Optional<Character>') to expected argument type 'String'
return string.last + string.substring(1, string.count - 2) + string.first // no exact matches in call to instance method 'substring'
return string.remove(.vowel) // no exact matches in call to instance method 'remove'
return string.remove(.vowel) // type 'String.Index' has no member 'vowel'
return string.remove(.vowel) // cannot convert return expression of type 'Character' to return type 'String'
func flipCase(string: String) -> String {
let result = ""
for char in string {
if char.isLowercase {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
func countVowels(string: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
func isPalindrome(string: String) -> Bool {
let reversed = String(string.reversed())
return string == reversed
}
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let result = ""
for char in string {
if char.isLowercase {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
// 2. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels(string: "Celebration") == 5
func countVowels(string: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
// 3. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "yummy") == false
func isPalindrome(string: String) -> Bool {
let reversed = String(string.reversed())
return string == reversed
}
// 4. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 5. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 6. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 7. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 8. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 9. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 10. Write a function that takes a string and returns a new string with the first and last characters swapped.
// swapEnds(string: "Hello") == "oellH"
func swapEnds(string: String) -> String {
let first = string.first()
let last = string.last()
let middle = string.substring(1, string.count - 2)
return last + middle + first
}
// 11. Write a function that takes a string and returns a new string with the first and last characters sw
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
let first = string.first() // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
let last = string.last() // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
let middle = string.substring(1, string.count - 2) // no exact matches in call to instance method 'substring'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercase
} else {
return $0.lowercase
}
}
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercase
} else {
return $0.lowercase
}
}
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.11.2
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.1
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.2
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.4
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.6
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.7
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.8
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1.12.9
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
return string.map { // cannot convert return expression of type '[T]' to return type 'String'
return $0.uppercase // value of type 'String.Element' (aka 'Character') has no member 'uppercase'
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(string: String) -> String {
var result = ""
for char in string {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(string: "I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck.
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func flipCase(string: String) -> String {
let result = ""
for char in string {
if char.isLowercase {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let result = ""
for char in string {
if char.isLowercase {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined()
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
return $0.uppercaseString // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined
}
func countVowels(string: String) -> Int {
return string.count(.Vowel)
}
func countConsonants(string: String) -> Int {
return string.count(.Consonant)
}
func countWords(string: String) -> Int {
return string.count(.Word)
}
func countSentences(string: String) -> Int {
return string.count(.Sentence)
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map {
if $0.isLowercase {
return $0.uppercaseString
} else {
return $0.lowercaseString
}
}.joined
}
// -----------------------------------------------------------------------------
// 1.1.2. Write a function that takes a string and returns the number of vowels in the string.
// countVowels(string: "Hello") == 2
func countVowels(string: String) -> Int {
return string.count(.Vowel)
}
// -----------------------------------------------------------------------------
// 1.1.3. Write a function that takes a string and returns the number of consonants in the string.
// countConsonants(string: "Hello") == 3
func countConsonants(string: String) -> Int {
return string.count(.Consonant)
}
// -----------------------------------------------------------------------------
// 1.1.4. Write a function that takes a string and returns the number of words in the string.
// countWords(string: "Hello world") == 2
func countWords(string: String) -> Int {
return string.count(.Word)
}
// -----------------------------------------------------------------------------
// 1.1.5. Write a function that takes a string and returns the number of sentences in the string.
// countSentences(string: "Hello world. How are you?") == 2
func countSentences(string: String) -> Int {
return string.count(.Sentence)
}
// -----------------------------------------------------------------------------
// 1.1.6. Write a function that takes a string and returns the number of emojis in the string.
// countEmojis(string: "😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😎 😍 😘 🤗 🤩 🤔 🤐 😯 😦 😧 😨 😰 😧 😢 😭 🤯 😱 😖 😣 😓 😞 😟 😤 😪 🤤 😴 🤐 🤢 🤧 🤕 🤑 🤗 🤔 🤐 🤓 😎 🤩 🤔 🤐 🤓 🤨 🤦♀️ 🤷♂️ 🤷♂️ 🤵 🤶 🤷 🤵♀️ 🤵♂️ 🤵♂️ 🤷♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵♂️ 🤵
return $0.uppercaseString // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
}.joined // function produces expected type 'String'; did you mean to call it with '()'?
return string.count(.Vowel) // cannot infer contextual base in reference to member 'Vowel'
return string.count(.Vowel) // cannot call value of non-function type 'Int'
return string.count(.Consonant) // cannot call value of non-function type 'Int'
return string.count(.Consonant) // cannot infer contextual base in reference to member 'Consonant'
return string.count(.Word) // cannot call value of non-function type 'Int'
return string.count(.Word) // cannot infer contextual base in reference to member 'Word'
return string.count(.Sentence) // cannot infer contextual base in reference to member 'Sentence'
return string.count(.Sentence) // cannot call value of non-function type 'Int'
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator
public func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator
public func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator
public func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// -----------------------------------------------------------------------------
// MARK: - String.join
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - String.join(separator: separator:)
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - String.join(separator: separator:, maxLength: maxLength:,
// truncation: truncation:, trim: trim:,
// truncationLocation: truncationLocation:,
// truncationSubstitution: truncationSubstitution:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncationSubstitutionLocation: truncationSubstitutionLocation:,
// truncationSubstitutionLength: truncationSubstitutionLength:,
// truncation
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
public func concatenate(strings: [String]) -> String {
return strings.joined(separator
public func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
// @testable
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns a new string with all the
// vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
return input.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(input: String) -> String {
return input.filter { !isVowel($0) }
}
// ----------------------------------------------------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all vowels removed.
//
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
return input.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 1.1.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.154.155.156.157.158.159.160.161.162.163.164.165.166.167.168.169.170.171.172.173.174.175.176.177.178.179.180.181.182.183.184.185.186.187.188.189.190.191.192.193.194.195.196.197.198.199.200.201.202.203.204.205.206.207.208.209.210.211.212.213.214.215.216.217.218.219.220.221.222.223.224.225.226.227.228.229.230.231.232.233.234.235.236.237.238.239.240.241.242.243.244.245.246.247.248.249.250.251.252.253.254.255.256.257.258.259.260.261.262.263.264.265.266.267.268.269.2
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all
// characters in the original string except the first and last ones.
// Example:
// reverseString("abcdef") == "bcd"
// reverseString("a") == ""
// reverseString("") == ""
// reverseString("ab") == "a"
// reverseString("abc") == "bc"
// reverseString("abcd") == "bc"
// reverseString("abcde") == "bcde"
// reverseString("abcdefg") == "bcdef"
// reverseString("abcdefgh") == "bcdefg"
// reverseString("abcdefghi") == "bcdefgh"
// reverseString("abcdefghij") == "bcdefghi"
// reverseString("abcdefghijkl") == "bcdefghij"
// reverseString("abcdefghijklm") == "bcdefghijkl"
// reverseString("abcdefghijklmn") == "bcdefghijklm"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "bcdefghijklmno"
// reverseString("abcdefghijklmno") == "
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 1.1.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
func countVowels(string: String) -> Int {
return string.count(.Vowel)
}
func countWords(string: String) -> Int {
return string.count(.Word)
}
func countUppercaseLetters(string: String) -> Int {
return string.count(.UpperCaseLetter)
}
func countLowercaseLetters(string: String) -> Int {
return string.count(.LowerCaseLetter)
}
func countDigits(string: String) -> Int {
return string.count(.Digit)
}
func countLettersAndDigits(string: String) -> (Int, Int) {
return (string.count(.Letter), string.count(.Digit))
}
func countVowelWords(string: String) -> Int {
return string.count(.VowelWord)
}
func countVowelWords(string: String) -> Int {
return string.count(.VowelWordEnd)
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of vowels in it.
// countVowels("apple") == 2
// countVowels("banana") == 3
func countVowels(string: String) -> Int {
return string.count(.Vowel)
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hello world, how are you?") == 4
func countWords(string: String) -> Int {
return string.count(.Word)
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of uppercase letters in it.
// countUppercaseLetters("Hello world") == 2
// countUppercaseLetters("Hello world, how are you?") == 3
func countUppercaseLetters(string: String) -> Int {
return string.count(.UpperCaseLetter)
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of lowercase letters in it.
// countLowercaseLetters("Hello world") == 8
// countLowercaseLetters("Hello world, how are you?") == 14
func countLowercaseLetters(string: String) -> Int {
return string.count(.LowerCaseLetter)
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of digits in it.
// countDigits("Hello world") == 0
// countDigits("Hello world, how are you?") == 2
func countDigits(string: String) -> Int {
return string.count(.Digit)
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number of letters and digits in it.
// countLettersAndDigits("Hello world") == (8, 0)
// countLettersAndDigits("Hello world, how are you?") == (14, 2)
func countLettersAndDigits(string: String) -> (Int, Int) {
return (string.count(.Letter), string.count(.Digit))
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns the number of words that start with a vowel.
// countVowelWords("Hello world") == 1
// countVowelWords("Hello world, how are you?") == 2
func countVowelWords(string: String) -> Int {
return string.count(.VowelWord)
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns the number of words that end with a vowel.
// countVowelWords("Hello world") == 1
// countVowelWords("Hello world, how are you?") == 2
func countVowelWords(string: String) -> Int {
return string.count(.VowelWordEnd)
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
return string.count(.Vowel) // cannot infer contextual base in reference to member 'Vowel'
return string.count(.Vowel) // cannot call value of non-function type 'Int'
return string.count(.Word) // cannot call value of non-function type 'Int'
return string.count(.Word) // cannot infer contextual base in reference to member 'Word'
return string.count(.UpperCaseLetter) // cannot call value of non-function type 'Int'
return string.count(.UpperCaseLetter) // cannot infer contextual base in reference to member 'UpperCaseLetter'
return string.count(.LowerCaseLetter) // cannot call value of non-function type 'Int'
return string.count(.LowerCaseLetter) // cannot infer contextual base in reference to member 'LowerCaseLetter'
return string.count(.Digit) // cannot infer contextual base in reference to member 'Digit'
return string.count(.Digit) // cannot call value of non-function type 'Int'
return (string.count(.Letter), string.count(.Digit)) // cannot infer contextual base in reference to member 'Letter'
return (string.count(.Letter), string.count(.Digit)) // cannot call value of non-function type 'Int'
return (string.count(.Letter), string.count(.Digit)) // cannot infer contextual base in reference to member 'Digit'
return (string.count(.Letter), string.count(.Digit)) // cannot call value of non-function type 'Int'
return string.count(.VowelWord) // cannot infer contextual base in reference to member 'VowelWord'
return string.count(.VowelWord) // cannot call value of non-function type 'Int'
func countVowelWords(string: String) -> Int { // invalid redeclaration of 'countVowelWords(string:)'
return string.count(.VowelWordEnd) // cannot infer contextual base in reference to member 'VowelWordEnd'
return string.count(.VowelWordEnd) // cannot call value of non-function type 'Int'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
func filterLongerThan(strings: [String], minLength: Int) -> [String] {
return strings.filter { $0.length > minLength }
}
func filterShorterThan(strings: [String], maxLength: Int) -> [String] {
return strings.filter { $0.length < maxLength }
}
func filterVowels(strings: [String], vowels: String) -> [String] {
return strings.filter { $0.first!.isVowel }
}
func filterConsonants(strings: [String], vowels: String) -> [String] {
return strings.filter { !$0.first!.isVowel }
}
func filterA(strings: [String], letter: String) -> [String] {
return strings.filter { $0.contains(letter) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes an array of strings and returns a new array
// containing only the strings that are longer than 5 characters.
// filterLongerThan(strings: [] as [String], minLength: 5) == [] as [String]
// filterLongerThan(strings: ["abc", "bcd", "cde", "array"], minLength: 5) == ["cde", "array"]
func filterLongerThan(strings: [String], minLength: Int) -> [String] {
return strings.filter { $0.length > minLength }
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an array of strings and returns a new array
// containing only the strings that are shorter than 5 characters.
// filterShorterThan(strings: [] as [String], maxLength: 5) == [] as [String]
// filterShorterThan(strings: ["abc", "bcd", "cde", "array"], maxLength: 5) == ["abc"]
func filterShorterThan(strings: [String], maxLength: Int) -> [String] {
return strings.filter { $0.length < maxLength }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of strings and returns a new array
// containing only the strings that start with a vowel.
// filterVowels(strings: [] as [String], vowels: "aeiou") == [] as [String]
// filterVowels(strings: ["abc", "bcd", "cde", "array"], vowels: "aeiou") == ["abc", "bcd", "cde"]
func filterVowels(strings: [String], vowels: String) -> [String] {
return strings.filter { $0.first!.isVowel }
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of strings and returns a new array
// containing only the strings that do not start with a vowel.
// filterConsonants(strings: [] as [String], vowels: "aeiou") == [] as [String]
// filterConsonants(strings: ["abc", "bcd", "cde", "array"], vowels: "aeiou") == ["array"]
func filterConsonants(strings: [String], vowels: String) -> [String] {
return strings.filter { !$0.first!.isVowel }
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of strings and returns a new array
// containing only the strings that contain the letter "a".
// filterA(strings: [] as [String], letter: "a") == [] as [String]
// filterA(strings: ["abc", "bcd", "cde", "array"], letter: "a") == ["abc", "bcd", "cde"]
func filterA(strings: [String], letter: String) -> [String] {
return strings.filter { $0.contains(letter) }
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes an array of strings and returns a new array
// containing only the strings that do not contain the letter "a".
// filterNotA(strings: [] as [String], letter: "a"
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
return strings.filter { $0.length > minLength } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
return strings.filter { $0.length < maxLength } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
return strings.filter { $0.first!.isVowel } // value of type 'String.Element' (aka 'Character') has no member 'isVowel'
return strings.filter { !$0.first!.isVowel } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 1.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
// -----------------------------------------------------------------------------
// 1.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
func countVowels(string: String) -> Int {
return string.count(.vowel)
}
func countWords(string: String) -> Int {
return string.split(.whitespace).count
}
func countConsonants(string: String) -> Int {
return string.count(.consonant)
}
func countUppercaseLetters(string: String) -> Int {
return string.count(.uppercaseLetter)
}
func countLowercaseLetters(string: String) -> Int {
return string.count(.lowercaseLetter)
}
func countDigits(string: String) -> Int {
return string.count(.digit)
}
func countWordsStartingWithVowel(string: String) -> Int {
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.startsWith(prefix) }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of vowels in it.
// countVowels("apple") == 2
// countVowels("banana") == 3
func countVowels(string: String) -> Int {
return string.count(.vowel)
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("I love coding") == 3
func countWords(string: String) -> Int {
return string.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of consonants in it.
// countConsonants("apple") == 5
// countConsonants("banana") == 6
func countConsonants(string: String) -> Int {
return string.count(.consonant)
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of uppercase letters in it.
// countUppercaseLetters("Apple") == 1
// countUppercaseLetters("Banana") == 3
func countUppercaseLetters(string: String) -> Int {
return string.count(.uppercaseLetter)
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of lowercase letters in it.
// countLowercaseLetters("Apple") == 5
// countLowercaseLetters("Banana") == 3
func countLowercaseLetters(string: String) -> Int {
return string.count(.lowercaseLetter)
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number of digits in it.
// countDigits("12345") == 5
// countDigits("abcdef") == 0
func countDigits(string: String) -> Int {
return string.count(.digit)
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns the number of words that start with a vowel.
// countWordsStartingWithVowel("apple") == 1
// countWordsStartingWithVowel("banana") == 2
func countWordsStartingWithVowel(string: String) -> Int {
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns the number of words that end with a consonant.
// countWordsEndingWithConsonant("apple") == 1
// countWordsEndingWithConsonant("banana") == 2
func countWordsEndingWithConsonant(string: String) -> Int {
return string.split(.whitespace).filter { $0.last == "a" || $0.last == "e" || $0.last == "i" || $0.last == "o" || $0.
return strings.filter { $0.startsWith(prefix) } // value of type 'String' has no member 'startsWith'
return string.count(.vowel) // cannot call value of non-function type 'Int'
return string.count(.vowel) // cannot infer contextual base in reference to member 'vowel'
return string.split(.whitespace).count // no exact matches in call to instance method 'split'
return string.split(.whitespace).count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return string.count(.consonant) // cannot infer contextual base in reference to member 'consonant'
return string.count(.consonant) // cannot call value of non-function type 'Int'
return string.count(.uppercaseLetter) // cannot infer contextual base in reference to member 'uppercaseLetter'
return string.count(.uppercaseLetter) // cannot call value of non-function type 'Int'
return string.count(.lowercaseLetter) // cannot call value of non-function type 'Int'
return string.count(.lowercaseLetter) // cannot infer contextual base in reference to member 'lowercaseLetter'
return string.count(.digit) // cannot call value of non-function type 'Int'
return string.count(.digit) // cannot infer contextual base in reference to member 'digit'
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count // no exact matches in call to instance method 'split'
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func countVowels(s: String) -> Int {
return s.count(.vowel)
}
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of vowels in it.
// countVowels("Hello world") == 3
// countVowels("Hi") == 2
// countVowels("aA") == 2
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels("bcd") == 0
func countVowels(s: String) -> Int {
return s.count(.vowel)
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hi") == 1
// countWords("aA") == 1
// countWords("aeiou") == 1
// countWords("") == 0
// countWords("bcd") == 0
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hi") == 1
// countWords("aA") == 1
// countWords("aeiou") == 1
// countWords("") == 0
// countWords("bcd") == 0
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hi") == 1
// countWords("aA") == 1
// countWords("aeiou") == 1
// countWords("") == 0
// countWords("bcd") == 0
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hi") == 1
// countWords("aA") == 1
// countWords("aeiou") == 1
// countWords("") == 0
// countWords("bcd") == 0
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
// countWords("Hi") == 1
// countWords("aA") == 1
// countWords("aeiou") == 1
// countWords("") == 0
// countWords("bcd") == 0
func countWords(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number of words in it.
// countWords("Hello world") == 2
//
return s.count(.vowel) // cannot call value of non-function type 'Int'
return s.count(.vowel) // cannot infer contextual base in reference to member 'vowel'
return s.split(.whitespace).count // no exact matches in call to instance method 'split'
return s.split(.whitespace).count // type 'String.Element' (aka 'Character') has no member 'whitespace'
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// reverseString("a!b@c#d$e%f&g*h(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890") == "0987654321{z}~yxv^wc,./n[o{p}q|rs<t>u(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// reverseString("a!b@c#d$e%f&g*h(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890") == "0987654321{z}~yxv^wc,./n[o{p}q|rs<t>u(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// reverseString("a!b@c#d$e%f&g*h(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890") == "0987654321{z}~yxv^wc,./n[o{p}q|rs<t>u(i)j_k+l-m[n]o{p}q|r:s<t>u|v,w^x~y{z}1234567890"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("a b c") == "c
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// reverseString("a-b-c") == "c-b-a"
// reverseString("a.b.c") == "c.b.a"
// reverseString("a!b!c") == "c!b!a"
// reverseString("a,b,c") == "c,b,a"
// reverseString("a?b?c") == "c?b?a"
// reverseString("a:b:c") == "c:b:a"
// reverseString("a;b;c") == "c;b;a"
// reverseString("a(b(c)") == "c(b(a)"
// reverseString("a[b[c]") == "c[b[a]"
// reverseString("a{b{c}") == "c{b{a}"
// reverseString("a<b<c") == "c<b<a"
// reverseString("a>b>c") == "c>b>a"
// reverseString("a|b|c") == "c|b|a"
// reverseString("a~b~c") == "c~b~a"
// reverseString("a^b^c") == "c^b^a"
// reverseString("a`b`c") == "c`b`a"
// reverseString("a'b'c") == "c'b'a"
// reverseString("a\"b\"c") == "c\"b\"a"
// reverseString("a\\b\\c") == "c\\b\\a"
// reverseString("a/b/c") == "c/b/a"
// reverseString("a?b?c") == "c?b?a"
// reverseString("a:b:c") == "c:b:a"
// reverseString("a;b;c") == "c;b;a"
// reverseString("a(b(c)") == "c(b(a)"
// reverseString("a[b[c]") == "c[b[a]"
// reverseString("a{b{c}") == "c{b{a}"
// reverseString("a<b<c") == "c<b<a"
// reverseString("a>b>c") == "c>b>a"
// reverseString("a|b|c") == "c|b|a"
// reverseString("a~b~c") == "c~b~a"
// reverseString("a^b^c") == "c^b^a"
// reverseString("a`b`c") == "c`b`a"
// reverseString("a'b'c") == "c'b'a"
// reverseString("a\"b\"c") == "c\"b\"a"
// reverseString("a\\b\\c") == "c\\b\\a"
// reverseString("a/b/c") == "c/b/a"
// reverseString("a?b?c") == "c?b?a"
// reverseString("a:b:c") == "c:b:a"
// reverseString("a;b;c") == "c;b;a"
// reverseString("a(b(c)") == "c(b(a)"
// reverseString("a[b[
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 8. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
// ----------------------------------------------------------------------------------------------------------------------
// 9. Write a function that takes a string and returns the number (count) of vowels contained within it.
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func capitalize(s: String) -> String {
return s.first!.uppercaseString + s.substring(1)
}
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalize("hello") == "Hello"
// capitalize("") == ""
// capitalize("cat")
// capitalize("cat in the hat")
func capitalize(s: String) -> String {
return s.first!.uppercaseString + s.substring(1)
}
// 3. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 4. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 5. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 6. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 7. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 8. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
if i == 0 {
result += c.uppercaseString
} else {
result += c
}
}
return result
}
// 9. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeEachWord("hello") == "Hello"
// capitalizeEachWord("")
// capitalizeEachWord("cat in the hat")
func capitalizeEachWord(s: String) -> String {
var result = ""
for (i, c) in s.enumerate() {
return s.first!.uppercaseString + s.substring(1) // no exact matches in call to instance method 'substring'
return s.first!.uppercaseString + s.substring(1) // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
for (i, c) in s.enumerate() { // value of type 'String' has no member 'enumerate'
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// -----------------------------------------------------------------------------
// 1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "a" && $0 != "e" && $0 != "i" && $0 != "o" && $0 != "u" }
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(s: String) -> String {
return s.filter { $0 != "
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func vowelCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
func wordCount(s: String) -> Int {
var count = 0
for c in s {
if c == " " {
count += 1
}
}
return count + 1
}
func uppercaseCount(s: String) -> Int {
var count = 0
for c in s {
if c == c.uppercase {
count += 1
}
}
return count
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string and returns the number of vowels in the
// string.
// vowelCount("Hello") == 2
// vowelCount("Apple") == 2
// vowelCount("") == 0
// vowelCount("aeiou") == 5
// vowelCount("aeiouAEIOU") == 10
// vowelCount("aeiouAEIOUaeiouAEIOU") == 20
func vowelCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Write a function that takes a string and returns the number of words in the
// string.
// wordCount("Hello") == 1
// wordCount("Apple") == 1
// wordCount("") == 0
// wordCount("Hello, world!") == 2
// wordCount("Hello, world! Hello, world!") == 2
// wordCount("Hello, world! Hello, world! Hello, world!") == 3
func wordCount(s: String) -> Int {
var count = 0
for c in s {
if c == " " {
count += 1
}
}
return count + 1
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Write a function that takes a string and returns the number of uppercase
// letters in the string.
// uppercaseCount("Hello") == 1
// uppercaseCount("Apple") == 0
// uppercaseCount("") == 0
// uppercaseCount("Hello, world!") == 2
// uppercaseCount("Hello, world! Hello, world!") == 2
// uppercaseCount("Hello, world! Hello, world! Hello, world!") == 3
func uppercaseCount(s: String) -> Int {
var count = 0
for c in s {
if c == c.uppercase {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Write a function that takes a string and returns the number of lowercase
// letters in the string.
// lowercaseCount("Hello") == 5
// lowercaseCount("Apple") == 5
// lowercaseCount("") == 0
// lowercaseCount("Hello, world!") == 10
// lowercaseCount("Hello, world! Hello, world!") == 10
// lowercaseCount("Hello, world! Hello, world! Hello, world!") == 15
func lowercaseCount(s: String) -> Int {
var count = 0
for c in s {
if c == c.lowercase {
if c == c.uppercase { // value of type 'Character' has no member 'uppercase'
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a number as input and returns the sum of all
// the numbers from 1 to that number.
//
// sum(1) == 1
// sum(2) == 3
// sum(3) == 6
// sum(4) == 10
// sum(5) == 15
// sum(6) == 21
// sum(7) == 28
// sum(8) == 36
// sum(9) == 45
// sum(10) == 55
// sum(11) == 66
// sum(12) == 78
// sum(13) == 91
// sum(14) == 105
// sum(15) == 121
// sum(16) == 137
// sum(17) == 155
// sum(18) == 173
// sum(19) == 191
// sum(20) == 210
// sum(21) == 231
// sum(22) == 253
// sum(23) == 277
// sum(24) == 305
// sum(25) == 331
// sum(26) == 361
// sum(27) == 397
// sum(28) == 435
// sum(29) == 485
// sum(30) == 543
// sum(31) == 605
// sum(32) == 678
// sum(33) == 765
// sum(34) == 865
// sum(35) == 985
// sum(36) == 1118
// sum(37) == 1255
// sum(38) == 1416
// sum(39) == 1591
// sum(40) == 1779
// sum(41) == 1975
// sum(42) == 2182
// sum(43) == 2401
// sum(44) == 2640
// sum(45) == 2905
// sum(46) == 3195
// sum(47) == 3516
// sum(48) == 3885
// sum(49) == 4285
// sum(50) == 4703
// sum(51) == 5165
// sum(52) == 5728
// sum(53) == 6325
// sum(54) == 7018
// sum(55) == 7825
// sum(56) == 8650
// sum(57) == 9665
// sum(58) == 10816
// sum(59) == 12151
// sum(60) == 13696
// sum(61) == 15451
// sum(62) == 17416
// sum(63) == 19591
// sum(64) == 22060
// sum(65) == 24755
// sum(66) == 27721
// sum(67) == 31005
// sum(68) == 35486
// sum
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
// XCTAssertTrue failed
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("ab") == "ba"
// reverseString("abc") == "cba"
// reverseString("abcd") == "dcba"
// reverseString("abcdefg") == "gfedcba"
// reverseString("abcdefghijklmnopqrstuvwxyz") == "zyxwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2. Write a function that takes an integer as input, and returns the number of
// 1 bits it has (also known as the Hamming weight).
// numberOf1Bits(11) == 3
// numberOf1Bits(128) == 1
// numberOf1Bits(4) == 1
// numberOf1Bits(0) == 0
// numberOf1Bits(1) == 1
// numberOf1Bits(2147483647) == 31
// numberOf1Bits(2147483648) == 1
// numberOf1Bits(2147483649) == 1
// numberOf1Bits(2147483650) == 1
// numberOf1Bits(2147483651) == 1
// numberOf1Bits(2147483652) == 1
// numberOf1Bits(2147483653) == 1
// numberOf1Bits(2147483654) == 1
// numberOf1Bits(2147483655) == 1
// numberOf1Bits(2147483656) == 1
// numberOf1Bits(2147483657) == 1
// numberOf1Bits(2147483658) == 1
// numberOf1Bits(2147483659) == 1
// numberOf1Bits(2147483660) == 1
// numberOf1Bits(2147483661) == 1
// numberOf1Bits(2147483662) == 1
// numberOf1Bits(2147483663) == 1
// numberOf1Bits(2147483664) == 1
// numberOf1Bits(2147483665) == 1
// numberOf1Bits(2147483666) == 1
// numberOf1Bits(2147483667) == 1
// numberOf1Bits(2147483668) == 1
// numberOf1Bits(2147483669) == 1
// numberOf1Bits(2147483670) == 1
// number
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a number and returns the sum of all numbers
// from 1 up to and including that number.
// sum(1) == 1
// sum(2) == 2 + 1
// sum(3) == 3 + 1 + 2
// sum(4) == 4 + 1 + 2 + 3
// sum(5) == 5 + 1 + 2 + 3 + 4
// sum(6) == 6 + 1 + 2 + 3 + 4 + 5
// sum(7) == 7 + 1 + 2 + 3 + 4 + 5 + 6
// sum(8) == 8 + 1 + 2 + 3 + 4 + 5 + 6 + 7
// sum(9) == 9 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
// sum(10) == 10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
// sum(11) == 11 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
// sum(12) == 12 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11
// sum(13) == 13 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12
// sum(14) == 14 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13
// sum(15) == 15 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14
// sum(16) == 16 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15
// sum(17) == 17 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16
// sum(18) == 18 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17
// sum(19) == 19 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18
// sum(20) == 20 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19
// sum(21) == 21 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func vowels(string: String) -> Int {
var vowels = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
func consonants(string: String) -> Int {
var consonants = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
consonants += 1
}
}
return consonants
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of vowels in
// the string.
// vowels: a, e, i, o, u
// a case-insensitive.
// vowels("Hello") == 2
// vowels("Why do you ask?") == 4
// vowels("Why?") == 0
// vowels("C is cool") == 2
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of vowels in
// the string.
// vowels: a, e, i, o, u
// a case-insensitive.
// vowels("Hello") == 2
// vowels("Why do you ask?") == 4
// vowels("Why?") == 0
// vowels("C is cool") == 2
func vowels(string: String) -> Int {
var vowels = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns the number of consonants
// in the string.
// vowels: a, e, i, o, u
// a case-insensitive.
// consonants("Hello") == 3
// consonants("Why do you ask?") == 5
// consonants("Why?") == 1
// consonants("C is cool") == 3
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns the number of consonants
// in the string.
// vowels: a, e, i, o, u
// a case-insensitive.
// consonants("Hello") == 3
// consonants("Why do you ask?") == 5
// consonants("Why?") == 1
// consonants("C is cool") == 3
func consonants(string: String) -> Int {
var consonants = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
consonants += 1
}
}
return consonants
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number of words in
// the string.
// words: a sequence of characters separated by whitespace
// words("Hello world") == 2
// words("Hello") == 1
// words("Hello, world") == 2
// words("Hello, world!") == 2
// words("Hello, world!!!") == 2
// words("Hello, world!!!!") == 2
// words("Hello, world!!!!!") == 2
// words("Hello, world!!!!!!") == 2
// words("Hello, world!!!
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
func removeVowels(s: String) -> String {
var s' = s
for c in "aeiouAEIOU" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
func removeConsonants(s: String) -> String {
var s' = s
for c in "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("o a kwek") == " kwk"
func removeVowels(s: String) -> String {
var s' = s
for c in "aeiouAEIOU" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
// 2. Write a function that takes a string and returns a new string with all the consonants removed.
// removeConsonants("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdbr"
// removeConsonants("pear tree") == " pr t"
// removeConsonants("o a kwek") == " kwk"
func removeConsonants(s: String) -> String {
var s' = s
for c in "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
// 3. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("o a kwek") == " kwk"
func removeVowels(s: String) -> String {
var s' = s
for c in "aeiouAEIOU" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
// 4. Write a function that takes a string and returns a new string with all the consonants removed.
// removeConsonants("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdbr"
// removeConsonants("pear tree") == " pr t"
// removeConsonants("o a kwek") == " kwk"
func removeConsonants(s: String) -> String {
var s' = s
for c in "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" {
s' = s'.replacingOccurrences(with: c, with: "")
}
return s'
}
// 5. Write a function that takes a string and returns a new string with all
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
var s' = s // unterminated string literal
var s' = s // type annotation missing in pattern
s' = s'.replacingOccurrences(with: c, with: "") // extra argument 'with' in call
s' = s'.replacingOccurrences(with: c, with: "") // single-quoted string literal found, use '"'
s' = s'.replacingOccurrences(with: c, with: "") // consecutive statements on a line must be separated by ';'
s' = s'.replacingOccurrences(with: c, with: "") // instance method 'replacingOccurrences(of:with:options:range:)' requires that 'Character' conform to 'StringProtocol'
s' = s'.replacingOccurrences(with: c, with: "") // missing argument for parameter 'of' in call
return s' // unterminated string literal
var s' = s // type annotation missing in pattern
var s' = s // unterminated string literal
s' = s'.replacingOccurrences(with: c, with: "") // single-quoted string literal found, use '"'
s' = s'.replacingOccurrences(with: c, with: "") // extra argument 'with' in call
s' = s'.replacingOccurrences(with: c, with: "") // missing argument for parameter 'of' in call
s' = s'.replacingOccurrences(with: c, with: "") // consecutive statements on a line must be separated by ';'
s' = s'.replacingOccurrences(with: c, with: "") // instance method 'replacingOccurrences(of:with:options:range:)' requires that 'Character' conform to 'StringProtocol'
return s' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
continue
}
for j in 0..<l.count {
if l[i] < l[j] {
l[i], l[j] = l[j], l[i]
}
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
continue
}
for j in 0..<l.count {
if l[i] < l[j] {
l[i], l[j] = l[j], l[i]
}
}
}
return l'
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l[i], l[j] = l[j], l[i] // expected expression
l[i], l[j] = l[j], l[i] // consecutive statements on a line must be separated by ';'
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 != 0 {
l'[i] = l[i]
}
}
l'.sort()
for i in 0..<l.count {
if i % 3 == 0 {
l'[i] = l[i]
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 != 0 {
l'[i] = l[i]
}
}
l'.sort()
for i in 0..<l.count {
if i % 3 == 0 {
l'[i] = l[i]
}
}
return l'
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i] // unterminated string literal
l'.sort() // unterminated string literal
l'[i] = l[i] // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 == 0 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8,
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 != 0 {
l'[i] = l[i]
}
}
for i in 0..<l.count {
if i % 3 == 0 {
for j in 0..<l.count {
if l[j] < l[i] {
l[i] = l[j]
l[j] = l[i - 1]
}
}
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 3 != 0 {
l'[i] = l[i]
}
}
for i in 0..<l.count {
if i % 3 == 0 {
for j in 0..<l.count {
if l[j] < l[i] {
l[i] = l[j]
l[j] = l[i - 1]
}
}
}
}
return l'
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a string with all the
// letters in alphabetical order.
// sortLetters("hello") == "ehllo"
// sortLetters("apple") == "aellpp"
// sortLetters("zoo") == "oozz"
// sortLetters("") == ""
// sortLetters("a") == "a"
// sortLetters("zz") == "zz"
// sortLetters("zzz") == "zzzz"
// sortLetters("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'[i] = l[i] // unterminated string literal
return l' // unterminated string literal
func sortThird(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
result.append(l[i])
}
}
result.sort()
for i in 0..<l.count {
if i % 3 != 0 {
result.append(l[i])
}
}
return result
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
result.append(l[i])
}
}
result.sort()
for i in 0..<l.count {
if i % 3 != 0 {
result.append(l[i])
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var sorted = [Int]()
var sortedIndex = 0
for index in l.enumerated() {
if index.1 % 3 == 0 {
sorted.append(index.1)
} else {
sorted[sortedIndex] = index.1
sortedIndex += 1
}
}
return sorted
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var sorted = [Int]()
var sortedIndex = 0
for index in l.enumerated() {
if index.1 % 3 == 0 {
sorted.append(index.1)
} else {
sorted[sortedIndex] = index.1
sortedIndex += 1
}
}
return sorted
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
// Fatal error: Index out of range
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
return l.sorted().distinct()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted().distinct()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
return l.sorted().distinct() // value of type '[Int]' has no member 'distinct'
func unique(l: [Int]) -> [Int] {
return l.sorted().distinct()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted().distinct()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
return l.sorted().distinct() // value of type '[Int]' has no member 'distinct'
func unique(l: [Int]) -> [Int] {
return l.sorted(by: { $0 < $1 }).distinct()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted(by: { $0 < $1 }).distinct()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
return l.sorted(by: { $0 < $1 }).distinct() // value of type '[Int]' has no member 'distinct'
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var result = l
result.sort()
var unique = [Int]()
for i in result {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = l
result.sort()
var unique = [Int]()
for i in result {
if !unique.contains(i) {
unique.append(i)
}
}
return unique
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------
func unique(l: [Int]) -> [Int] {
var result = l
result.sort()
var i = 0
while i < result.count - 1 {
if result[i] == result[i + 1] {
result.remove(at: i)
} else {
i += 1
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = l
result.sort()
var i = 0
while i < result.count - 1 {
if result[i] == result[i + 1] {
result.remove(at: i)
} else {
i += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var sorted = l.sorted()
var result = [sorted.first!]
for i in 1..<sorted.count {
if sorted[i] != sorted[i - 1] {
result.append(sorted[i])
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var sorted = l.sorted()
var result = [sorted.first!]
for i in 1..<sorted.count {
if sorted[i] != sorted[i - 1] {
result.append(sorted[i])
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
var sorted = l.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func unique(l: [Int]) -> [Int] {
var result = l.sorted()
var i = 0
while i < result.count - 1 {
if result[i] == result[i + 1] {
result.remove(at: i)
} else {
i += 1
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = l.sorted()
var i = 0
while i < result.count - 1 {
if result[i] == result[i + 1] {
result.remove(at: i)
} else {
i += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
func maxElement(l: [Int]) -> Int {
return l.max()!
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return l.max()!
}
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
// maxElement
//
//
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
struct maxElementTests {
static let allTests: [UITestCase] = [
UITestCase(
name: "maxElement",
description: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
""",
expected: "3\n123",
actual: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
"""
)
]
}
struct maxElementTestsRunner: XCTestCase {
static func suite() -> XCTest {
return XCTest(
name: "maxElement",
description: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
""",
tests: maxElementTests.allTests
)
}
}
import Foundation
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
struct maxElementTests {
static let allTests: [UITestCase] = [
UITestCase(
name: "maxElement",
description: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
""",
expected: "3\n123",
actual: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
"""
)
]
}
// -----------------------------------------------------------------------------
struct maxElementTestsRunner: XCTestCase {
static func suite() -> XCTest {
return XCTest(
name: "maxElement",
description: """
maxElement(l: [1, 2, 3]) == 3
maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
""",
tests: maxElementTests.allTests
)
}
}<|endoftext|>//
// main.swift
// 10.1.1
//
// Created by Даниил on 10.04.2020.
// Copyright © 2020 Danil. All rights reserved.
//
import Foundation
// -----------------------------------------------------------------------------
// 1. Написать функцию, которая принимает на вход строку и возвращает
// новую строку, в которой каждый символ заменен на символ, который стоит
// на позиции символа в исходной строке.
//
// Пример:
//
// string("hello") == "olleh"
// string("bye") == "yb"
// string("") == ""
// string("a") == "a"
// -----------------------------------------------------------------------------
// 2. Написать функцию, которая принимает на вход строку и возвращает
// новую строку, в которой каждый символ заменен на символ, который стоит
// на позиции символа в исходной строке.
//
// Пример:
//
// string("hello") == "olleh"
// string("bye") == "yb"
// string("") == ""
// string("a") == "a"
// -----------------------------------------------------------------------------
// 3. Написать функцию, которая принимает на вход строку и возвращает
// новую строку, в которой каждый символ заменен на символ, который стоит
// на позиции символа в исходной строке.
//
// Пример:
//
//
static let allTests: [UITestCase] = [ // cannot find type 'UITestCase' in scope
struct maxElementTestsRunner: XCTestCase { // inheritance from non-protocol type 'XCTestCase'
static func suite() -> XCTest { // cannot find type 'XCTest' in scope
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
func addDigits(num: Int) -> Int {
if num < 10 {
return num
}
return num % 9 == 0 ? 9 : num % 9
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example:
// Input: 11
// Output: 3
// Explanation: 11 (1011) has binary representation 00011110 and contains three ones.
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
// Example:
// Input: 38
// Output: 2
// Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
// Since 2 has only one digit, return it.
func addDigits(num: Int) -> Int {
if num < 10 {
return num
}
return num % 9 == 0 ? 9 : num % 9
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Given a non-negative integer, repeatedly add all its digits until the result has only one digit.
// Example:
// Input: 38
// Output: 2
// Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
// Since 2 has only one digit, return it.
func addDigits(num: Int) -> Int {
if num < 10 {
return num
}
return num % 9 == 0 ? 9 : num % 9
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Given a non-negative integer, repeatedly add all its digits until the result has only one digit.
// Example:
// Input: 38
// Output: 2
// Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
// Since 2 has only one digit, return it.
func addDigits(num: Int) -> Int {
if num < 10 {
return num
}
return num % 9 == 0 ? 9 : num % 9
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Given a non-negative integer, repeatedly add all its digits until the result has only one digit.
// Example:
// Input: 38
// Output: 2
// Explanation: The process is like: 3 + 8
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func singleNumber(nums: [Int]) -> Int {
return nums.reduce(0, ^(let acc, let num) { acc ^= num })
}
func singleNumber2(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
func singleNumber3(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
func singleNumber4(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Given an array of integers, every element appears twice except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,1]
// Output: 1
func singleNumber(nums: [Int]) -> Int {
return nums.reduce(0, ^(let acc, let num) { acc ^= num })
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber2(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber3(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2,3,2]
// Output: 3
func singleNumber4(nums: [Int]) -> Int {
var ones = 0
var twos = 0
for num in nums {
ones = (ones ^ num) & ~twos
twos = (twos ^ num) & ~ones
}
return ones
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Given an array of integers, every element appears three times except for one. Find that single one.
// Note:
// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
// Example:
// Input: [2,2
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // 'let' cannot appear nested inside another 'var' or 'let' pattern
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // type annotation missing in pattern
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // expected expression
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // consecutive statements on a line must be separated by ';'
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // expected expression in list of expressions
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // type annotation missing in pattern
return nums.reduce(0, ^(let acc, let num) { acc ^= num }) // '^' is not a prefix unary operator
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func numberOf1Bits(n: Int) -> Int {
var count = 0
while n != 0 {
count += 1
n = n & (n - 1)
}
return count
}
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n != 0 {
count += 1
n = n & (n - 1)
}
return count
}
func numberOf7(n: Int) -> Int {
var count = 0
var num = n
while num != 0 {
if num % 10 == 7 {
count += 1
}
num /= 10
}
return count
}
func numberOfDigits(n: Int) -> Int {
var count = 0
var num = n
while num != 0 {
count += 1
num /= 10
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given input n = 00000000000000000000000000001011, return 3.
// Given input n = 00000000000000000000000010000000, return 1.
// Given input n = 11111111111111111111111111111101, return 31.
func numberOf1Bits(n: Int) -> Int {
var count = 0
while n != 0 {
count += 1
n = n & (n - 1)
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
// Example:
// The 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
func numberOf1Bits(n: UInt) -> Int {
var count = 0
while n != 0 {
count += 1
n = n & (n - 1)
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes an integer and returns the number of times the digit 7 appears in it.
// Example:
// For n = 717, the output should be 2;
// For n = 1234, the output should be 1.
// For n = 777777, the output should be 7.
func numberOf7(n: Int) -> Int {
var count = 0
var num = n
while num != 0 {
if num % 10 == 7 {
count += 1
}
num /= 10
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes an integer and returns the number of digits in it.
// Example:
// For n = 123, the output should be 3;
// For n = 52, the output should be 2.
func numberOfDigits(n: Int) -> Int {
var count = 0
var num = n
while num != 0 {
count += 1
num /= 10
}
return count
}
// ---------
n = n & (n - 1) // cannot assign to value: 'n' is a 'let' constant
n = n & (n - 1) // cannot assign to value: 'n' is a 'let' constant
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 17. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 18. Write a function that takes a string and returns a new string with the first and last characters swapped.
// fizzBuzz("Hello") == "oHell"
// fizzBuzz("Goodbye") == "Goodbye"
func fizzBuzz(s: String) -> String {
return String(characters: s.reversed())
}
return String(characters: s.reversed()) // no exact matches in call to initializer
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func reverseOdd(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
if i % 2 == 1 {
newStr += str[str.index(i)]
}
}
return newStr.reversed().join()
}
func reverse(str: String) -> String {
return str.reversed().join()
}
func capitalize(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].uppercase
}
return newStr
}
func lowercase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].lowercase
}
return newStr
}
func swapCase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].lowercase
}
return newStr
}
func swapCase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].uppercase
}
return newStr
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// 2. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters at odd indices reversed.
// reverseOdd("abcdef") == "aecdbf"
// reverseOdd("123456789") == "187532946"
func reverseOdd(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
if i % 2 == 1 {
newStr += str[str.index(i)]
}
}
return newStr.reversed().join()
}
// 3. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order.
// reverse("abcdef") == "fedcba"
// reverse("123456789") == "987654321"
func reverse(str: String) -> String {
return str.reversed().join()
}
// 4. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order and with the first character replaced by its uppercase equivalent.
// capitalize("abcdef") == "ABCDEF"
// capitalize("123456789") == "987654321"
func capitalize(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].uppercase
}
return newStr
}
// 5. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order and with the first character replaced by its lowercase equivalent.
// lowercase("ABCDEF") == "abcdef"
// lowercase("123456789") == "987654321"
func lowercase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].lowercase
}
return newStr
}
// 6. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order and with the first character replaced by its uppercase equivalent and the rest replaced by its lowercase equivalent.
// swapCase("abcdef") == "AbCdEf"
// swapCase("123456789") == "987654321"
func swapCase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].lowercase
}
return newStr
}
// 7. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order and with the first character replaced by its lowercase equivalent and the rest replaced by its uppercase equivalent.
// swapCase("abcdef") == "AbCdEf"
// swapCase("123456789") == "987654321"
func swapCase(str: String) -> String {
var newStr = ""
for i in 0..<str.count {
newStr += str[str.index(i)].uppercase
}
return newStr
}
// 8. Write a function that takes a string as an argument and returns a new string that contains the same characters as the original string but with the characters in reverse order and with the first character replaced by its lowercase equivalent and the rest replaced by its uppercase equivalent and the first character replaced
newStr += str[str.index(i)] // subscript 'subscript(_:)' requires that 'String.Index' conform to 'RangeExpression'
newStr += str[str.index(i)] // no exact matches in call to instance method 'index'
return newStr.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return str.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
newStr += str[str.index(i)].uppercase // no exact matches in call to instance method 'index'
newStr += str[str.index(i)].uppercase // value of type 'Character' has no member 'uppercase'
newStr += str[str.index(i)].lowercase // no exact matches in call to instance method 'index'
newStr += str[str.index(i)].lowercase // value of type 'Character' has no member 'lowercase'
newStr += str[str.index(i)].lowercase // no exact matches in call to instance method 'index'
newStr += str[str.index(i)].lowercase // value of type 'Character' has no member 'lowercase'
func swapCase(str: String) -> String { // invalid redeclaration of 'swapCase(str:)'
newStr += str[str.index(i)].uppercase // no exact matches in call to instance method 'index'
newStr += str[str.index(i)].uppercase // value of type 'Character' has no member 'uppercase'
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 11. Write a function that takes an integer and returns the number of 5's that appear in its binary representation.
// Example:
// countOnes(10) == 1
// countOnes(12) == 2
// countOnes(25) == 2
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// hammingWeight(11) == 3
// hammingWeight(128) == 1
// hammingWeight(4294967293) == 31
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// hammingWeight(11) == 3
// hammingWeight(128) == 1
// hammingWeight(4294967293) == 31
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// hammingWeight(11) == 3
// hammingWeight(128) == 1
// hammingWeight(4294967293) == 31
func hammingWeight(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// hammingWeight(11) == 3
// hammingWeight(128) == 1
// hammingWeight(4294967293) == 31
func hammingWeight(n: Int) -> Int {
var
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func findOdd(A: [Int]) -> Int {
var dict = [Int: Int]()
for i in A {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
for (key, value) in dict {
if value % 2 != 0 {
return key
}
}
return 0
}
func doubleChar(text: String) -> String {
var result = ""
for i in text {
result += String(i) + String(i)
}
return result
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// 2.
// Given an array of integers, find the one that appears an odd number of times.
//
// There will always be only one integer that appears an odd number of times.
//
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
func findOdd(A: [Int]) -> Int {
var dict = [Int: Int]()
for i in A {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
for (key, value) in dict {
if value % 2 != 0 {
return key
}
}
return 0
}
// 3.
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
//
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
func doubleChar(text: String) -> String {
var result = ""
for i in text {
result += String(i) + String(i)
}
return result
}
// 4.
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
//
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
func doubleChar(text: String) -> String {
var result = ""
for i in text {
result += String(i) + String(i)
}
return result
}
// 5.
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
//
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
func doubleChar(text: String) -> String {
var result = ""
for i in text {
result += String(i) + String(i)
}
return result
}
// 6.
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
//
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
func doubleChar(text: String) -> String {
var result = ""
for i in text {
result += String(i) + String(i)
}
return result
}
// 7.
// Given a string, you have to return a string in which each character (
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func doubleArrayValues(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 * 2 }
}
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// 2. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArrayValues(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 * 2 }
}
// 3. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 4. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 5. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 6. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 7. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 8. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 9. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 10. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 11. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 12. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// 13. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(inputArray: [Int]) -> [Int] {
return inputArray.map { $0 + 1 }
}
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1..<n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the number of vowels in the string.
// vowels("apple") == 2
// vowels("banana") == 3
// vowels("grapefruit") == 5
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") == 3
// vowels("kiwi") ==
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i-1]
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i-1]
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i] // unterminated string literal
l'[i] = l[i-1] // unterminated string literal
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'.sort()
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'.sort()
}
}
return l'
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i / 2]
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i / 2]
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i] // unterminated string literal
l'[i] = l[i / 2] // unterminated string literal
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
if i % 2 == 0 {
result.append(l[i])
} else {
result.append(l[i - 1])
}
}
return result
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
if i % 2 == 0 {
result.append(l[i])
} else {
result.append(l[i - 1])
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of vowels in the string.
// You may assume the string will always be in all lower case.
// You can assume the string will always be a valid string.
// vowelCount("apple") == 2
// vowelCount("cheese") == 4
// vowelCount("sillystring") == 4
// vowelCount("12345") == 0
// vowelCount("") == 0
// vowelCount("aeiou") == 5
// vowelCount("aeiouaeiou") == 10
// vowelCount("aeiouaeiouaeiouaeiou") == 20
// vowelCount("aeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouae
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i/2]
}
}
for i in 1..<l.count {
if i % 2 == 1 {
for j in 1..<i {
if l[j] > l[i] {
l[j], l[i] = l[i], l[j]
}
}
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i/2]
}
}
for i in 1..<l.count {
if i % 2 == 1 {
for j in 1..<i {
if l[j] > l[i] {
l[j], l[i] = l[i], l[j]
}
}
}
}
return l'
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i/2] // unterminated string literal
l[j], l[i] = l[i], l[j] // expected expression
l[j], l[i] = l[i], l[j] // consecutive statements on a line must be separated by ';'
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'.insert(l[i], at: i)
}
}
return l'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'.insert(l[i], at: i)
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
var l' = l // unterminated string literal
var l' = l // type annotation missing in pattern
l'.insert(l[i], at: i) // unterminated string literal
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
}
}
for i in 0..<l.count {
if i % 2 == 1 {
l'.sort()
}
}
return l'
}
func sumEven(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 0 {
sum += l[i]
}
}
return sum
}
func sumOdd(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 1 {
sum += l[i]
}
}
return sum
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 1..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
}
}
for i in 0..<l.count {
if i % 2 == 1 {
l'.sort()
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the even indicies.
// sumEven([1, 2, 3]) == 2
// sumEven([5, 6, 3, 4]) == 10
func sumEven(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 0 {
sum += l[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the odd indicies.
// sumOdd([1, 2, 3]) == 3
// sumOdd([5, 6, 3, 4]) == 12
func sumOdd(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 1 {
sum += l[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the even indicies.
// sumEven([1, 2, 3]) == 2
// sumEven([5, 6, 3, 4]) == 10
func sumEven(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 0 {
sum += l[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the odd indicies.
// sumOdd([1, 2, 3]) == 3
// sumOdd([5, 6, 3, 4]) == 12
func sumOdd(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 1 {
sum += l[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the even indicies.
// sumEven([1, 2, 3]) == 2
// sumEven([5, 6, 3, 4]) == 10
func sumEven(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if i % 2 == 0 {
sum += l[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Given an array l, return the sum of the elements at the odd indicies.
// sumOdd([1, 2, 3]) == 3
// sumOdd([5, 6, 3, 4])
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i] // unterminated string literal
l'.sort() // unterminated string literal
return l' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i / 2]
}
}
return l'
}
func vowels(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
func removeVowels(s: String) -> String {
var s' = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
s' += c
}
}
return s'
}
func isPalindrome(s: String) -> Bool {
var s' = ""
for c in s {
s' = c + s'
}
return s == s'
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l' = l
for i in 0..<l.count {
if i % 2 == 0 {
l'[i] = l[i]
} else {
l'[i] = l[i / 2]
}
}
return l'
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of vowels in the string.
// You may assume the string will contain only lowercase letters.
// vowels("apple") == 2
// vowels("cheese") == 4
// vowels("sillystring") == 5
func vowels(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all the vowels removed.
// You may assume the string will contain only lowercase letters.
// removeVowels("apple") == "ppl"
// removeVowels("cheese") == "chs"
// removeVowels("sillystring") == "slystrng"
func removeVowels(s: String) -> String {
var s' = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
s' += c
}
}
return s'
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and returns true if the string is a palindrome, false otherwise.
// You may assume the string will contain only lowercase letters.
// isPalindrome("abba") == true
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(s: String) -> Bool {
var s' = ""
for c in s {
s' = c + s'
}
return s == s'
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all the vowels removed.
// You may assume the string will contain only lowercase letters.
// removeVowels("apple") == "ppl"
// removeVowels("cheese") == "chs"
// removeVowels("sillystring") == "slystrng"
func removeVowels(s: String) -> String {
var s' = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
s' += c
}
}
return s'
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and returns true if the string is a palindrome, false otherwise.
// You may assume the string will contain only lowercase letters.
// isPalindrome("abba")
var l' = l // type annotation missing in pattern
var l' = l // unterminated string literal
l'[i] = l[i] // unterminated string literal
l'[i] = l[i / 2] // unterminated string literal
return l' // unterminated string literal
var s' = "" // type annotation missing in pattern
var s' = "" // unterminated string literal
s' += c // unterminated string literal
return s' // unterminated string literal
var s' = "" // unterminated string literal
var s' = "" // type annotation missing in pattern
s' = c + s' // single-quoted string literal found, use '"'
s' = c + s' // consecutive statements on a line must be separated by ';'
return s == s' // unterminated string literal
func sortEven(l: [Int]) -> [Int] {
var l2 = l
for i in 0..<l.count {
if i % 2 == 0 {
l2[i] = l[i]
} else {
l2[i] = l[i/2]
}
}
l2.sort()
return l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l2 = l
for i in 0..<l.count {
if i % 2 == 0 {
l2[i] = l[i]
} else {
l2[i] = l[i/2]
}
}
l2.sort()
return l2
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var result = l
for i in 1..<l.count {
if i % 2 == 0 {
result[i] = l[i/2]
}
}
for i in 1..<l.count {
if i % 2 == 1 {
result[i] = l[i/2]
}
}
return result
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var result = l
for i in 1..<l.count {
if i % 2 == 0 {
result[i] = l[i/2]
}
}
for i in 1..<l.count {
if i % 2 == 1 {
result[i] = l[i/2]
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [Int]()
var prime = [Int]()
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
while fib.count < n {
fib.append(i)
i = j + k
j = k
k = i
}
while prime.count < n {
if fib[l] % 2 == 0 {
prime.append(fib[l])
}
l++
}
return prime[n - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [Int]()
var prime = [Int]()
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
while fib.count < n {
fib.append(i)
i = j + k
j = k
k = i
}
while prime.count < n {
if fib[l] % 2 == 0 {
prime.append(fib[l])
}
l++
}
return prime[n - 1]
}
print(primeFib(1))
print(primeFib(2))
print(primeFib(3))
print(primeFib(4))
print(primeFib(5))
print(primeFib(6))
print(primeFib(7))
print(primeFib(8))
print(primeFib(9))
print(primeFib(10))
print(primeFib(11))
print(primeFib(12))
print(primeFib(13))
print(primeFib(14))
print(primeFib(15))
print(primeFib(16))
print(primeFib(17))
print(primeFib(18))
print(primeFib(19))
print(primeFib(20))
print(primeFib(21))
print(primeFib(22))
print(primeFib(23))
print(primeFib(24))
print(primeFib(25))
print(primeFib(26))
print(primeFib(27))
print(primeFib(28))
print(primeFib(29))
print(primeFib(30))
print(primeFib(31))
print(primeFib(32))
print(primeFib(33))
print(primeFib(34))
print(primeFib(35))
print(primeFib(36))
print(primeFib(37))
print(primeFib(38))
print(primeFib(39))
print(primeFib(40))
print(primeFib(41))
print(primeFib(42))
print(primeFib(43))
print(primeFib(44))
print(primeFib(45))
print(primeFib(46))
print(primeFib(47))
print(primeFib(48))
print(primeFib(49))
print(primeFib(50))
print(primeFib(51))
print(primeFib(52))
print(primeFib(53))
print(primeFib(54))
print(primeFib(55))
print(primeFib(56))
print(primeFib(57))
print(primeFib(58))
print(primeFib(59))
print(primeFib(60))
print(primeFib(61))
print(primeFib(62))
print(primeFib(63))
print(primeFib(64))
print(primeFib(65))
print(primeFib(66))
print(primeFib(67))
print(primeFib(68))
print(primeFib(69))
print(primeFib(70))
print(primeFib(71))
print(primeFib(72))
print(primeFib(73))
print(primeFib(74))
print(primeFib(75))
print(primeFib(76))
print(primeFib(77))
print(primeFib(78))
print(primeFib(79))
print(primeFib
l++ // cannot find operator '++' in scope; did you mean '+= 1'?
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[j] < n {
if isPrime(fib[j]) {
return fib[j]
}
j += 1
}
return fib[j - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[j] < n {
if isPrime(fib[j]) {
return fib[j]
}
j += 1
}
return fib[j - 1]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------
if isPrime(fib[j]) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 1
while n > 0 {
c = a + b
if isPrime(c) {
a = b
b = c
} else {
a = b
b = c
}
n -= 1
}
return c
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 1
var b = 1
var c = 1
while n > 0 {
c = a + b
if isPrime(c) {
a = b
b = c
} else {
a = b
b = c
}
n -= 1
}
return c
}
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK: - Tests
// -----------------------------------------------------------------------------
// MARK: - Helpers
// -----------------------------------------------------------------------------
// MARK:
if isPrime(c) { // cannot find 'isPrime' in scope
n -= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i]
}
import Foundation
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i]
}
print(primeFib(1000))<|endoftext|>//
// main.swift
// 1480
//
// Created by 윤승현 on 2021/09/22.
//
import Foundation
// 1480. Running Sum of 1d Array
// https://leetcode.com/problems/running-sum-of-1d-array/
// 배열의 각 요소는 앞에서부터 1씩 증가하는 숫자로 이루어져 있다.
// 배열의 요소를 순회하면서 앞에서부터 증가하는 숫자의 합을 구하는 프로그램을 작성하라.
// 예제 1
// Input: nums = [1,2,3,4]
// Output: [1,3,6,10]
// Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
// 예제 2
// Input: nums = [1,1,1,1,1]
// Output: [1,2,3,4,5]
// Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
// 예제 3
// Input: nums = [3,1,2,10,1]
// Output: [3,4,6,16,17]
// 제한사항
// 1 <= nums.length <= 1000
// -10^6 <= nums[i] <= 10^6
// 풀이
// 배열의 각 요소를 순회하면서 앞에서부터 증가하는 숫자의 합을 구하는 프로그램을 작성하라.
// 제한사항
// 배열의 길이는 1 이상 1000 이하이다.
// 배열의 요소는 -10^6 이상 10^6 이하이다.
// 제한사항
// 배열의 각 요소는 앞에서부터 1씩 증가하는 숫자로 이루어져 있다.
// 배열의 요소를 순회하면서 앞에서부터 증가하는 숫자의 합을 구하는 프로그램을 작성하라.
// 예제 1
// Input: nums = [1,2,3,4]
// Output: [1,3,6,10]
// Explanation: Running sum is obtained as follows: [1, 1+2, 1+
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[i - 1] + fib[i - 2] < n {
j += 1
i += 1
}
return fib[j]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[i - 1] + fib[i - 2] < n {
j += 1
i += 1
}
return fib[j]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i - 1]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
return fib[i]
}
print(primeFib(1))
print(primeFib(2))
print(primeFib(3))
print(primeFib(4))
print(primeFib(5))
print(primeFib(6))
print(primeFib(7))
print(primeFib(8))
print(primeFib(9))
print(primeFib(10))
print(primeFib(11))
print(primeFib(12))
print(primeFib(13))
print(primeFib(14))
print(primeFib(15))
print(primeFib(16))
print(primeFib(17))
print(primeFib(18))
print(primeFib(19))
print(primeFib(20))
print(primeFib(21))
print(primeFib(22))
print(primeFib(23))
print(primeFib(24))
print(primeFib(25))
print(primeFib(26))
print(primeFib(27))
print(primeFib(28))
print(primeFib(29))
print(primeFib(30))
print(primeFib(31))
print(primeFib(32))
print(primeFib(33))
print(primeFib(34))
print(primeFib(35))
print(primeFib(36))
print(primeFib(37))
print(primeFib(38))
print(primeFib(39))
print(primeFib(40))
print(primeFib(41))
print(primeFib(42))
print(primeFib(43))
print(primeFib(44))
print(primeFib(45))
print(primeFib(46))
print(primeFib(47))
print(primeFib(48))
print(primeFib(49))
print(primeFib(50))
print(primeFib(51))
print(primeFib(52))
print(primeFib(53))
print(primeFib(54))
print(primeFib(55))
print(primeFib(56))
print(primeFib(57))
print(primeFib(58))
print(primeFib(59))
print(primeFib(60))
print(primeFib(61))
print(primeFib(62))
print(primeFib(63))
print(primeFib(64))
print(primeFib(65))
print(primeFib(66))
print(primeFib(67))
print(primeFib(68))
print(primeFib(69))
print(primeFib(70))
print(primeFib(71))
print(primeFib(72))
print(primeFib(73))
print(primeFib(74))
print(primeFib(75))
print(primeFib(76))
print(primeFib(77))
print(primeFib(78))
print(primeFib(79))
print(primeFib(80))
print(primeFib(81))
print(primeFib(82))
print(primeFib(83))
print(primeFib(84))
print(primeFib(85))
print(primeFib(86))
print(primeFib(87))
print(primeFib(88))
print(primeFib(89))
print(primeFib(90))
print(primeFib(91))
print(primeFib(92))
print(primeFib(93))
print(primeFib(94))
print(primeFib(95))
print(prime
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[j] < n {
if isPrime(fib[j]) {
return fib[j]
}
j += 1
}
return fib[j - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] + fib[i - 2] < n {
fib.append(fib[i - 1] + fib[i - 2])
i += 1
}
var j = 0
while fib[j] < n {
if isPrime(fib[j]) {
return fib[j]
}
j += 1
}
return fib[j - 1]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
if isPrime(fib[j]) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i] < n {
fib[i] = fib[i - 1] + fib[i - 2]
i += 1
}
return fib[i - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [1, 1]
var i = 2
while fib[i] < n {
fib[i] = fib[i - 1] + fib[i - 2]
i += 1
}
return fib[i - 1]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] < n {
fib[i] = fib[i - 1] + fib[i - 2]
i += 1
}
return fib[i - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [0, 1]
var i = 2
while fib[i - 1] < n {
fib[i] = fib[i - 1] + fib[i - 2]
i += 1
}
return fib[i - 1]
}
print(primeFib(1)) // 2
print(primeFib(2)) // 3
print(primeFib(3)) // 5
print(primeFib(4)) // 13
print(primeFib(5)) // 89
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var result = false
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
result = true
break
}
}
if result {
break
}
}
if result {
break
}
}
return result
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var result = false
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
result = true
break
}
}
if result {
break
}
}
if result {
break
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count {
for j in i+1..<l.count {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sum2 = sum / 3
var count = 0
for i in l {
if i == sum2 {
count += 1
}
}
if count >= 3 {
return true
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sum2 = sum / 3
var count = 0
for i in l {
if i == sum2 {
count += 1
}
}
if count >= 3 {
return true
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
var sum2 = sum / 3 // variable 'sum2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sumToFind = sum / 3
var left = 0
var right = l.count - 1
while left < right {
var leftSum = l[left] + l[right]
if leftSum == sumToFind {
return true
} else if leftSum < sumToFind {
left += 1
} else {
right -= 1
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sumToFind = sum / 3
var left = 0
var right = l.count - 1
while left < right {
var leftSum = l[left] + l[right]
if leftSum == sumToFind {
return true
} else if leftSum < sumToFind {
left += 1
} else {
right -= 1
}
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
var sumToFind = sum / 3 // variable 'sumToFind' was never mutated; consider changing to 'let' constant
var leftSum = l[left] + l[right] // variable 'leftSum' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var result = false
if l.count > 2 {
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
result = true
break
}
}
}
}
}
return result
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var result = false
if l.count > 2 {
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
result = true
break
}
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of integers and returns the sum of
// the integers.
// sum(l: [1, 2, 3]) == 6
// sum(l: [1, 2, 3, 4]) == 10
// sum(l: [1, 2, 3, 4, 5]) == 15
// sum(l: [1, 2, 3, 4, 5, 6]) == 21
// sum(l: [1, 2, 3, 4, 5, 6, 7]) == 28
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8]) == 36
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9]) == 45
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 66
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 78
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 91
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 105
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 121
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 137
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 155
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 173
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 191
// sum(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sum_to_find = sum / 3
var count = 0
var i = 0
var j = 0
var k = 0
while i < l.count {
j = i + 1
while j < l.count {
k = j + 1
while k < l.count {
if l[i] + l[j] + l[k] == sum_to_find {
count += 1
}
k += 1
}
j += 1
}
i += 1
}
if count > 0 {
return true
} else {
return false
}
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
var sum = 0
for i in l {
sum += i
}
if sum % 3 != 0 {
return false
}
var sum_to_find = sum / 3
var count = 0
var i = 0
var j = 0
var k = 0
while i < l.count {
j = i + 1
while j < l.count {
k = j + 1
while k < l.count {
if l[i] + l[j] + l[k] == sum_to_find {
count += 1
}
k += 1
}
j += 1
}
i += 1
}
if count > 0 {
return true
} else {
return false
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
var input = [1, 3, 5, 0]
print(triplesSumToZero(input))
input = [1, 3, -2, 1]
print(triplesSumToZero(input))
input = [1, 2, 3, 7]
print(triplesSumToZero(input))
input = [2, 4, -5, 3, 9, 7]
print(triplesSumToZero(input))
input = [1]
print(triplesSumToZero(input))<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
// be [2, 3, 6].
//
// Follow-up: what if you can't use division?
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
var sum_to_find = sum / 3 // variable 'sum_to_find' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// your code here
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count-2 {
for j in i+1..<l.count-1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
// -----------------------------------------------------------------------------
// 1.1
// Given two strings, write a method to decide if one is a permutation of the
// other.
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dcab") == false
// isPermutation("abcd", "dcba") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcabd") == false
// isPermutation("abcd", "dcab
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count - 2 {
for j in i+1..<l.count - 1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
if l.count < 3 {
return false
}
for i in 0..<l.count - 2 {
for j in i+1..<l.count - 1 {
for k in j+1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i
}
return result
}
func countLetters(s: String) -> Int {
var result = 0
for c in s {
if c.isUpper {
result += 1
}
if c.isLower {
result += 1
}
}
return result
}
func sumArray(arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result
}
func maxArray(arr: [Int]) -> Int {
var result = arr[0]
for i in arr {
if i > result {
result = i
}
}
return result
}
func minArray(arr: [Int]) -> Int {
var result = arr[0]
for i in arr {
if i < result {
result = i
}
}
return result
}
func avgArray(arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result / arr.count
}
func prodArray(arr: [Int]) -> Int {
var result = 1
for i in arr {
result *= i
}
return result
}
func countEven(arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 == 0 {
result += 1
}
}
return result
}
func countOdd(arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 != 0 {
result += 1
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i
}
return result
}
// 10. Write a function that takes a string as input and returns the number of
// uppercase letters and lowercase letters.
// Example:
// Input: "Hello, World!"
// Output: 3
func countLetters(s: String) -> Int {
var result = 0
for c in s {
if c.isUpper {
result += 1
}
if c.isLower {
result += 1
}
}
return result
}
// 11. Write a function that takes an array of integers as input and returns the
// sum of all the integers in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 15
func sumArray(arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result
}
// 12. Write a function that takes an array of integers as input and returns the
// maximum integer in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 5
func maxArray(arr: [Int]) -> Int {
var result = arr[0]
for i in arr {
if i > result {
result = i
}
}
return result
}
// 13. Write a function that takes an array of integers as input and returns the
// minimum integer in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 1
func minArray(arr: [Int]) -> Int {
var result = arr[0]
for i in arr {
if i < result {
result = i
}
}
return result
}
// 14. Write a function that takes an array of integers as input and returns the
// average of all the integers in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 3
func avgArray(arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result / arr.count
}
// 15. Write a function that takes an array of integers as input and returns the
// product of all the integers in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 120
func prodArray(arr: [Int]) -> Int {
var result = 1
for i in arr {
result *= i
}
return result
}
// 16. Write a function that takes an array of integers as input and returns the
// number of even integers in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 2
func countEven(arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 == 0 {
result += 1
}
}
return result
}
// 17. Write a function that takes an array of integers as input and returns the
// number of odd integers in the array.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 3
func countOdd(arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 != 0 {
result += 1
}
}
return result
}
// 18. Write a function that takes an array of integers as input and returns the
// number of integers in the array that are greater than 0.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: 3
func countPositive(arr: [Int]) -> Int {
var result = 0
for i in arr {
if i >
if c.isUpper { // value of type 'Character' has no member 'isUpper'
if c.isLower { // value of type 'Character' has no member 'isLower'
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in 1...n {
if i != j {
result += 1
}
}
}
return result
}
func countLetters(s: String) -> (uppercase: Int, lowercase: Int) {
var uppercase = 0
var lowercase = 0
for c in s {
if c.isUpper {
uppercase += 1
} else {
lowercase += 1
}
}
return (uppercase, lowercase)
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
if n & 1 == 1 {
result += 1
}
n >>= 1
}
return result
}
func countSetBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
func countBits(n: Int) -> [Int] {
var result = [0, 0]
while n > 0 {
result[n & 1] += 1
n >>= 1
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in 1...n {
if i != j {
result += 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the number of
// uppercase letters and lowercase letters.
// Example:
// Input: "Hello, World!"
// Output: 3
func countLetters(s: String) -> (uppercase: Int, lowercase: Int) {
var uppercase = 0
var lowercase = 0
for c in s {
if c.isUpper {
uppercase += 1
} else {
lowercase += 1
}
}
return (uppercase, lowercase)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// reversed.
// Example:
// Input: "hello"
// Output: "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an integer as input and returns the number of
// bits that are equal to one in the binary representation of that number.
// Example:
// Input: 7
// Output: 3
// Explanation: 7 is 111 and has binary representation 111.
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
if n & 1 == 1 {
result += 1
}
n >>= 1
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an integer as input and returns the number of
// bits that are equal to one in the binary representation of that number,
// excluding any leading zero bits.
// Example:
// Input: 11
// Output: 3
// Explanation: 11 is 1011 and has binary representation 1011.
// There are three ones, so return 3.
func countSetBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an integer as input and returns the number of
// bits that are equal to one in the binary representation of that number,
// then returns the number of bits that are equal to zero in the binary
// representation of that number.
// Example:
// Input: 7
// Output: [3, 0]
// Explanation: 7 is 111 and has binary representation 111.
// So the returned array should be [3, 0]
func countBits(n: Int) -> [Int] {
var result = [0, 0]
while n > 0 {
result[n & 1] += 1
n >>= 1
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes an integer as input and returns the number of
// bits that are equal to one in the binary representation of that number,
// then returns the number of bits that are equal to zero in the binary
// representation of that number.
// Example:
// Input: 7
// Output: [3, 0]
// Explanation: 7 is 111 and has binary representation 111.
// So the returned array should be [3,
if c.isUpper { // value of type 'Character' has no member 'isUpper'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i * (n - i)
}
return result
}
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit(char) {
currentNumber += char
} else if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
func maxPalindrome(s: String) -> Int {
var result = 0
var currentPalindrome = ""
for char in s {
currentPalindrome += char
if currentPalindrome == currentPalindrome.reversed() {
result = max(result, currentPalindrome.length)
}
}
return result
}
func longestPalindromeDelete(s: String) -> Int {
var result = 0
var currentPalindrome = ""
for char in s {
currentPalindrome += char
if currentPalindrome == currentPalindrome.reversed() {
result = max(result, currentPalindrome.length)
}
if currentPalindrome.length > 1 && currentPalindrome[0] == currentPalindrome[1] {
currentPalindrome = currentPalindrome[1..]
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i * (n - i)
}
return result
}
// 2.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
//
// Examples:
// "abc123xyz" → 123
// "aa11b33" → 44
// "7 11" → 22
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit(char) {
currentNumber += char
} else if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
// 3.
// Given a string, return the length of the longest palindrome that can be made using
// letters from the string.
//
// For example, maxPalindrome("aaabaaa") → 9
// maxPalindrome("abccbaitf") → 3
// maxPalindrome("abccba") → 7
func maxPalindrome(s: String) -> Int {
var result = 0
var currentPalindrome = ""
for char in s {
currentPalindrome += char
if currentPalindrome == currentPalindrome.reversed() {
result = max(result, currentPalindrome.length)
}
}
return result
}
// 4.
// Given a string, return the length of the longest palindrome that can be made
// by deleting exactly one character from the string.
//
// For example, longestPalindromeDelete("aaabaaa") → 7
// longestPalindromeDelete("abccbaitf") → 5
// longestPalindromeDelete("abccba") → 7
func longestPalindromeDelete(s: String) -> Int {
var result = 0
var currentPalindrome = ""
for char in s {
currentPalindrome += char
if currentPalindrome == currentPalindrome.reversed() {
result = max(result, currentPalindrome.length)
}
if currentPalindrome.length > 1 && currentPalindrome[0] == currentPalindrome[1] {
currentPalindrome = currentPalindrome[1..]
}
}
return result
}
// 5.
// Given a string, return the length of the longest palindrome that can be made
// by deleting exactly one character from the string.
//
// For example, longestPalindromeDelete("aaabaaa") → 7
// longestPalindromeDelete("abccbaitf") → 5
// longestPalindromeDelete("abccba") → 7
func longestPalindromeDelete(s: String) -> Int {
var result = 0
var currentPalindrome = ""
for char in s {
currentPalindrome += char
if currentPalindrome == currentPalindrome.reversed() {
result = max(result, currentPalindrome.length)
}
if currentPalindrome.length > 1 && currentPalindrome[0] == currentPalindrome[1] {
currentPalindrome = currentPalindrome[1..]
}
}
return result
}
// 6.
// Given a string, return the length of the longest palindrome that can be made
// by deleting exactly one character from the string.
//
// For example, longestPalindromeDelete("aaabaaa") → 7
// longestPalindromeDelete("abccbaitf") → 5
// longestPalindromeDelete("abccba
if char.isDigit(char) { // value of type 'Character' has no member 'isDigit'
currentNumber += char // cannot convert value of type 'Character' to expected argument type 'String'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
currentPalindrome += char // cannot convert value of type 'Character' to expected argument type 'String'
if currentPalindrome == currentPalindrome.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
result = max(result, currentPalindrome.length) // value of type 'String' has no member 'length'
currentPalindrome += char // cannot convert value of type 'Character' to expected argument type 'String'
if currentPalindrome == currentPalindrome.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
result = max(result, currentPalindrome.length) // value of type 'String' has no member 'length'
if currentPalindrome.length > 1 && currentPalindrome[0] == currentPalindrome[1] { // value of type 'String' has no member 'length'
currentPalindrome = currentPalindrome[1..] // cannot find operator '..' in scope; did you mean '...'?
func carRaceCollision(n: Int) -> Int {
let cars = [Int(0), Int(0)]
let collisions = 0
for i in 0..<n {
cars[i % 2] += 1
if cars[i % 2] == cars[(i + 1) % 2] {
collisions += 1
}
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
let cars = [Int(0), Int(0)]
let collisions = 0
for i in 0..<n {
cars[i % 2] += 1
if cars[i % 2] == cars[(i + 1) % 2] {
collisions += 1
}
}
return collisions
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------
cars[i % 2] += 1 // left side of mutating operator isn't mutable: 'cars' is a 'let' constant
collisions += 1 // left side of mutating operator isn't mutable: 'collisions' is a 'let' constant
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
result += i * (n - i)
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
result += i * (n - i)
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2. A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like madam I'M Adam.
// The challenge is to write the shortest function that determines whether a
// given string of characters is a palindrome.
// -----------------------------------------------------------------------------
// A palindrome is a word that's spelled the same forward and backward.
// For example, radar is a palindrome. Some palindromic words are spelled like
// madam, madam I'm Adam. Others, like alex, are spelled like mad
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var collisions = 0
for i in 1...n {
collisions += n - i
}
return collisions
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var collisions = 0
for i in 1...n {
collisions += n - i
}
return collisions
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given a string, return the length of the longest substring without repeating
// characters.
// For example, the longest substring without repeating letters for "abcabcbb"
// is "abc", which the length is 3.
// For "bbbbb" the longest substring is "b", with the length of 1.
//
// Example 1:
// Input: "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
//
// Example 2:
// Input: "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given a string s, find the length of the longest substring without repeating characters.
//
// Example 1:
// Input: "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
//
// Example 2:
// Input: "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
//
// Example 3:
// Input: "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
//
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
//
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
//
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
//
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
//
//
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i
}
return result
}
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
result += i
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the number of
// times that a particular character appears in the string.
// For example, given the input "apple", your function should return 2.
// Hint: you may find the built-in string method count(of:_) helpful.
func countChar(str: String, char: Character) -> Int {
return str.count(of: char)
}
return str.count(of: char) // cannot call value of non-function type 'Int'
func carRaceCollision(n: Int) -> Int {
var leftToRight = 0
var rightToLeft = 0
for i in 1...n {
leftToRight += i
rightToLeft += n - i + 1
}
return leftToRight * rightToLeft
}
import Foundation
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var leftToRight = 0
var rightToLeft = 0
for i in 1...n {
leftToRight += i
rightToLeft += n - i + 1
}
return leftToRight * rightToLeft
}
print(carRaceCollision(3))<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
sum += num
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
if num % 2 == 0 {
sum += num
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
if num % 2 == 0 {
sum += num
} else {
sum -= num
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
if num % 2 == 0 {
sum += num
} else {
sum -= num
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
if num % 2 == 0 {
sum += num
} else {
sum -= num
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for num in nums {
if num % 2 == 0 {
sum += num
} else {
sum -= num
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 윤선우 on 2022/04/02.
//
import Foundation
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9,
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in 1...n {
if i < j {
result += 1
}
}
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
}
return result
}
func containsDuplicate(nums: [Int]) -> Bool {
var result = false
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j {
if nums[i] == nums[j] {
result = true
}
}
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1...n {
for j in 1...n {
if i < j {
result += 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Given an array of integers, find if the array contains any duplicates.
// Your function should return true if any value appears at least twice in the array,
// and it should return false if every element is distinct.
func containsDuplicate(nums: [Int]) -> Bool {
var result = false
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j {
if nums[i] == nums[j] {
result = true
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in 1..<n {
if i != j {
result += 1
}
}
}
return result
}
func sumNumbers(s: String) -> Int {
var result = 0
var i = 0
var j = 0
while i < s.length {
while j < s.length && s[j] != " " {
j += 1
}
var num = 0
while i < s.length && s[i] != " " {
num = num * 10 + Int(s[i]) - 48
i += 1
}
result += num
i += 1
j += 1
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in 1..<n {
if i != j {
result += 1
}
}
}
return result
}
// 2. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
//
// Example:
// Input: "abc123xyz"
// Output: 123
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "aa11b33"
// Output: 4
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "7 11"
// Output: 18
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "a"
// Output: 0
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
func sumNumbers(s: String) -> Int {
var result = 0
var i = 0
var j = 0
while i < s.length {
while j < s.length && s[j] != " " {
j += 1
}
var num = 0
while i < s.length && s[i] != " " {
num = num * 10 + Int(s[i]) - 48
i += 1
}
result += num
i += 1
j += 1
}
return result
}
// 3. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
//
// Example:
// Input: "abc123xyz"
// Output: 123
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "aa11b33"
// Output: 4
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "7 11"
// Output: 18
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
//
// Example:
// Input: "a"
// Output: 0
//
// Hint:
// Use two pointers: one to find the start of the next number, and one to find the end of the next number.
func sumNumbers(s: String) -> Int {
var result = 0
var i = 0
var j = 0
while i < s.length {
while j < s.length && s[j] != " " {
j += 1
}
var num = 0
while i < s.length && s[i] != " " {
num = num * 10 + Int(s[i]) - 48
i += 1
}
result += num
i += 1
j += 1
}
return result
}
// 4
while i < s.length { // value of type 'String' has no member 'length'
while j < s.length && s[j] != " " { // value of type 'String' has no member 'length'
while i < s.length && s[i] != " " { // value of type 'String' has no member 'length'
num = num * 10 + Int(s[i]) - 48 // no exact matches in call to initializer
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// 1.1.2
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("Vowels") to get a set of all the
// vowels.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("Vowels") to get a set of all the
// vowels.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("Vowels") to get a set of all the
// vowels.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("Vowels") to get a set of all the
// vowels.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("Vowels") to get a set of all the
// vowels.
//
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
//
// Write a function that takes a string and returns a new string with all the
// vowels removed.
//
// For example, removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
//
// Hint: You can use the characterSetNamed("V
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// 1.2.1.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// 1.10.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] = l[i] + 1
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// MARK: - 1.3.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.2.
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
// be [2, 3, 6].
//
// Follow-up: what if you can't use division?
//
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
// be [2, 3, 6].
//
// Follow-up: what if you can't use division?
//
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
// be [2, 3, 6].
//
// Follow-up: what if you can't use division?
//
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would
// be [2, 3, 6].
//
// Follow-up: what if you can't use division?
//
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array such that each element at
// index i of the new array is the product of all the numbers in the original
// array except the one at i.
//
// For example, if our input was
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
func countVowels(s: String) -> Int {
var count = 0
for i in s {
if i == "a" || i == "e" || i == "i" || i == "o" || i == "u" {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
var count = 0
for i in s {
if i != " " {
count += 1
}
}
return count
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
// 1.1.2
// Write a function that takes a string as an input and returns the number of vowels in the string.
// Vowels are the letters 'a', 'e', 'i', 'o', and 'u'.
// countVowels("apple") == 2
// countVowels("hello world") == 3
// countVowels("h") == 0
// countVowels("") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in s {
if i == "a" || i == "e" || i == "i" || i == "o" || i == "u" {
count += 1
}
}
return count
}
// 1.1.3
// Write a function that takes a string as an input and returns the number of words in the string.
// A word is defined as a sequence of non-whitespace characters surrounded by whitespace or the beginning or end of the string.
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
// countWords("Hello world! ") == 2
// countWords("") == 0
// countWords(" ") == 0
func countWords(s: String) -> Int {
var count = 0
for i in s {
if i != " " {
count += 1
}
}
return count
}
// 1.1.4
// Write a function that takes a string as an input and returns the number of sentences in the string.
// A sentence is defined as a sequence of non-whitespace characters surrounded by whitespace or the beginning or end of the string.
// countSentences("Hello world!") == 1
// countSentences("Hello world! ") == 1
// countSentences("Hello world! .") == 1
// countSentences("Hello world! . ") == 1
// countSentences("Hello world! . .") == 1
// countSentences("Hello world! . . ") == 1
// countSentences("Hello world! . . .") == 1
// countSentences("Hello world! . . . ") == 1
// countSentences("Hello world! . . . .") == 1
// countSentences("Hello world! . . . . ") == 1
// countSentences("Hello world! . . . . .") == 1
// countSentences("Hello world! . . . . . ") == 1
// countSentences("Hello world! . . . . . .") == 1
// countSentences("Hello world! . . . . . . ") == 1
// countSentences("Hello world! . . . . . . .") == 1
// countSentences("Hello world! . . . . . . . ") == 1
// countSentences("Hello world! . . . . . . . .") == 1
// countSentences("Hello world! . . . . . . . ..") == 1
// countSentences("Hello world! . . . . . . . ...") == 1
// countSentences("Hello world! . . . . . . . ....") == 1
// countSentences("Hello world! . . . . . . . .....") == 1
// countSentences("Hello world! . . .
func pairsSumToZero(l: [Int]) -> Bool {
var result = false
for i in 0..<l.count-1 {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
result = true
break
}
}
if result {
break
}
}
return result
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var result = false
for i in 0..<l.count-1 {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
result = true
break
}
}
if result {
break
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------------
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i * -1) {
return true
}
seen.insert(i)
}
return false
}
func isUnivalueList(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return false
}
seen.insert(i)
}
return true
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i * -1) {
return true
}
seen.insert(i)
}
return false
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// is_univalue_list takes an input list of integers.
// it returns true if the list is univalue (all elements are the same),
// and false otherwise.
// isUnivalueList(l: [1, 1, 1]) == true
// isUnivalueList(l: [1, 2, 1]) == false
// isUnivalueList(l: [1, 1, 2]) == false
// isUnivalueList(l: [1]) == true
// isUnivalueList(l: []) == true
func isUnivalueList(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in l {
if seen.contains(i) {
return false
}
seen.insert(i)
}
return true
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// is_linked_list_palindrome takes an input list of integers.
// it returns true if the list is a palindrome, and false otherwise.
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1]) == true
// isLinkedListPalindrome(l: [1, 2, 3, 2, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 3, 2, 1]) == true
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 2, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 2, 2]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 2, 2, 1]) == false
// isLinkedListPalindrome(l: [1, 2, 3, 2, 1, 2, 1, 2, 2, 2
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in 0..<l.count {
if i == j {
continue
}
if l[i] + l[j] == 0 {
return true
}
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
for i in 0..<l.count {
for j in 0..<l.count {
if i == j {
continue
}
if l[i] + l[j] == 0 {
return true
}
}
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
func pairsSumToZero(l: [Int]) -> Bool {
var sum = 0
for i in l {
if sum == 0 {
return true
}
sum += i
}
return false
}
func isUnivalue(l: [Int]) -> Bool {
var first = l[0]
for i in l {
if first != i {
return false
}
}
return true
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var sum = 0
for i in l {
if sum == 0 {
return true
}
sum += i
}
return false
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// is_univalue takes an array of integers as an input.
// it returns true if all elements in the array are the same, and false otherwise.
// isUnivalue([1, 1, 1, 1, 1]) == true
// isUnivalue([1, 2, 1, 1, 1]) == false
// isUnivalue([1, 1, 2, 1, 1]) == false
// isUnivalue([1, 1, 1, 2, 1]) == false
// isUnivalue([1, 1, 1, 1]) == true
// isUnivalue([1]) == true
func isUnivalue(l: [Int]) -> Bool {
var first = l[0]
for i in l {
if first != i {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// is_strictly_increasing takes an array of integers as an input.
// it returns true if the array is strictly increasing, and false otherwise.
// isStrictlyIncreasing([1, 2, 3, 4, 5]) == true
// isStrictlyIncreasing([1, 2, 3, 4, 5, 6]) == true
// isStrictlyIncreasing([1, 2, 3, 4, 5, 5]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6]) == false
// isStrictlyIncreasing([1, 2, 3, 4, 5, 4, 3, 2, 1, 0, -1, -2, -3,
var first = l[0] // variable 'first' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
func sumArray(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func sumOfEven(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOdd(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 != 0 {
sum += i
}
}
return sum
}
func sumOfGreaterThanFive(l: [Int]) -> Int {
var sum = 0
for i in l {
if i > 5 {
sum += i
}
}
return sum
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in l {
if l.contains(i * -1) {
count += 1
}
}
return count > 1
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an array of integers as an input and returns
// the sum of all the integers in the array.
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, 2, 3, 4, 5]) == 12
// sumArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sumArray([-1, -2, -3, -4, -5]) == -15
// sumArray([]) == 0
func sumArray(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes an array of integers as an input and returns
// the sum of all the even integers in the array.
// sumOfEven([1, 2, 3, 4, 5]) == 6
// sumOfEven([-1, 2, 3, 4, 5]) == 6
// sumOfEven([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 30
// sumOfEven([-1, -2, -3, -4, -5]) == 0
// sumOfEven([]) == 0
func sumOfEven(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i
}
}
return sum
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an array of integers as an input and returns
// the sum of all the odd integers in the array.
// sumOfOdd([1, 2, 3, 4, 5]) == 9
// sumOfOdd([-1, 2, 3, 4, 5]) == 9
// sumOfOdd([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 25
// sumOfOdd([-1, -2, -3, -4, -5]) == 0
// sumOfOdd([]) == 0
func sumOfOdd(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 != 0 {
sum += i
}
}
return sum
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes an array of integers as an input and returns
// the sum of all the integers in the array that are greater than 5.
// sumOfGreaterThanFive([1, 2, 3, 4, 5]) == 15
// sumOfGreaterThanFive([-1, 2, 3, 4, 5]) == 15
// sumOfGreaterThanFive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 30
// sumOfGreaterThanFive([-1, -2, -3, -4, -5]) == 0
// sumOfGreaterThanFive([]) == 0
func sumOfGreaterThanFive(l: [Int]) -> Int {
var sum = 0
for i in l {
if i > 5 {
sum += i
}
}
return sum
}
func pairsSumToZero(l: [Int]) -> Bool {
var result = false
for i in 0..<l.count-1 {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
result = true
break
}
}
if result {
break
}
}
return result
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var result = false
for i in 0..<l.count-1 {
for j in i+1..<l.count {
if l[i] + l[j] == 0 {
result = true
break
}
}
if result {
break
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string as an input and returns the number of
// times each letter appears in the string.
// countLetters("hello") == {"h": 1, "e": 1, "l": 2, "o": 1}
// countLetters("") == {"": 1}
// countLetters("a") == {"a": 1}
// countLetters("aa") == {"a": 2}
// countLetters("aab") == {"a": 2, "b": 1}
// countLetters("aabb") == {"a": 2, "b": 2}
// countLetters("aabbcc") == {"a": 2, "b": 2, "c": 2}
// countLetters("aabbccddee") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2}
// countLetters("aabbccddeeff") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1}
// countLetters("aabbccddeeffg") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1}
// countLetters("aabbccddeeffgg") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2}
// countLetters("aabbccddeeffggh") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2, "h": 1}
// countLetters("aabbccddeeffggghi") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2, "h": 1, "i": 1}
// countLetters("aabbccddeeffggghiij") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2, "h": 1, "i": 2, "j": 1}
// countLetters("aabbccddeeffggghiijj") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2, "h": 1, "i": 2, "j": 2, "k": 1}
// countLetters("aabbccddeeffggghiijjk") == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 2, "h": 1, "i": 2, "j": 2, "k": 2, "l": 1}
// countLetters("aabbccddeeffggghiijjkk" == {"a": 2, "b": 2, "c": 2, "d": 2, "e": 2,
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(num * -1) {
return true
}
seen.insert(num)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for num in l {
if seen.contains(num * -1) {
return true
}
seen.insert(num)
}
return false
}
// 1.1
// Given two strings, write a method to decide if one is a permutation of the other.
// permutation(s1: "abcd", s2: "dcba") == true
// permutation(s1: "abcd", s2: "dcbaa") == false
// permutation(s1: "abcd", s2: "dc") == false
// permutation(s1: "abcd", s2: "") == false
// permutation(s1: "abcd", s2: "abc") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
// permutation(s1: "abcd", s2: "abcde") == false
//
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in 0..<l.count {
for j in 0..<l.count {
if i == j {
continue
}
if l[i] + l[j] == 0 {
count += 1
}
}
}
return count > 0
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var count = 0
for i in 0..<l.count {
for j in 0..<l.count {
if i == j {
continue
}
if l[i] + l[j] == 0 {
count += 1
}
}
}
return count > 0
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder = remainder / base
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder = remainder / base
}
return result
}
// 2.
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 4.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the most significant bit (the sign bit).
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countSetBits(1234) == 5
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 5.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the most significant bit (the sign bit).
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countSetBits(1234) == 5
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 6.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the most significant bit (the sign bit).
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countSetBits(1234) == 5
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 7.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the most significant bit (the sign bit).
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countSetBits(1234) == 5
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 8.
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the most significant bit (the sign bit).
// Example: The binary representation of 1234 is 10011010010, so the
n = n / 2 // cannot assign to value: 'n' is a 'let' constant
n = n / 2 // cannot assign to value: 'n' is a 'let' constant
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// 1.2
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.3
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.4
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.5
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.6
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.7
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.8
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prnng Dt Ck n scl."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char) {
result += char
}
}
return result
}
// 1.9
// Write a function that takes a string and returns a string with all the vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn
x /= base // left side of mutating operator isn't mutable: 'x' is a 'let' constant
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func changeBase(x: Int, base: Int) -> String {
var result = ""
var current = x
while current > 0 {
result = String(current % base) + result
current /= base
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var current = x
while current > 0 {
result = String(current % base) + result
current /= base
}
return result
}
// 1.10
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.11
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.12
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.13
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.14
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.15
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.16
// Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels("I am a student") == " m stdn"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 1.17
//
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// 1.1.2
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 1.1.3
// Write a function that takes an integer as input and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.4
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.5
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.6
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.7
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.8
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
var result = 0
while n > 0 {
result += n & 1
n >>= 1
}
return result
}
// 1.1.9
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return
x /= base // left side of mutating operator isn't mutable: 'x' is a 'let' constant
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func changeBase(x: Int, base: Int) -> String {
var result = ""
var current = x
while current > 0 {
result = String(current % base) + result
current /= base
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var current = x
while current > 0 {
result = String(current % base) + result
current /= base
}
return result
}
// 2.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 3.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 4.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 5.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 6.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 7.
// Given a string, return the string with all the vowels removed.
// removeVowels("I love coding") == " lvcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I love coding") == " lvcdng"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char !
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder /= base
}
return result
}
// 1.10
// 1.11
// 1.12
// 1.13
// 1.14
// 1.15
// 1.16
// 1.17
// 1.18
// 1.19
// 1.20
// 1.21
// 1.22
// 1.23
// 1.24
// 1.25
// 1.26
// 1.27
// 1.28
// 1.29
// 1.30
// 1.31
// 1.32
// 1.33
// 1.34
// 1.35
// 1.36
// 1.37
// 1.38
// 1.39
// 1.40
// 1.41
// 1.42
// 1.43
// 1.44
// 1.45
// 1.46
// 1.47
// 1.48
// 1.49
// 1.50
// 1.51
// 1.52
// 1.53
// 1.54
// 1.55
// 1.56
// 1.57
// 1.58
// 1.59
// 1.60
// 1.61
// 1.62
// 1.63
// 1.64
// 1.65
// 1.66
// 1.67
// 1.68
// 1.69
// 1.70
// 1.71
// 1.72
// 1.73
// 1.74
// 1.75
// 1.76
// 1.77
// 1.78
// 1.79
// 1.80
// 1.81
// 1.82
// 1.83
// 1.84
// 1.85
// 1.86
// 1.87
// 1.88
// 1.89
// 1.90
// 1.91
// 1.92
// 1.93
// 1.94
// 1.95
// 1.96
// 1.97
// 1.98
// 1.99
// 2.00
// 2.01
// 2.02
// 2.03
// 2.04
// 2.05
// 2.06
// 2.07
// 2.08
// 2.09
// 2.10
// 2.11
// 2.12
// 2.13
// 2.14
// 2.15
// 2.16
// 2.17
// 2.18
// 2.19
// 2.20
// 2.21
// 2.22
// 2.23
// 2.24
// 2.25
// 2.26
// 2.27
// 2.28
// 2.29
// 2.30
// 2.31
// 2.32
// 2.33
// 2.34
// 2.35
// 2.36
// 2.37
// 2.38
// 2.39
// 2.40
// 2.41
// 2.42
// 2.43
// 2.44
// 2.45
// 2.46
// 2.47
// 2.
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var remainder = x
while remainder > 0 {
result = String(remainder % base) + result
remainder /= base
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------------
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
x /= base // left side of mutating operator isn't mutable: 'x' is a 'let' constant
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number /= base
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
while number > 0 {
result = String(number % base) + result
number /= base
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("apple") == "ppl"
func vowelFree(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
//
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // cannot use mutating member on immutable value: 'str' is a 'let' constant
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // missing argument label 'with:' in call
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // value of tuple type '()' has no member 'replace'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
func changeCase(input: String) -> String {
return input.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.joined()
}
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
func multiplyArray(array: [Int]) -> Int {
return array.reduce(1, { $0 * $1 })
}
func multiplicationTable(number: Int) -> String {
var result = ""
for i in 1...10 {
result += "\(i) * \(number) = \(i * number)\n"
}
return result
}
func findOdd(array: [Int]) -> Int {
return array.filter { $0 % 2 == 1 }.first!
}
func reverseString(input: String) -> String {
return input.reversed().join()
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case " ==> "cASE HElLO "
// " " ==> ""
// "" ==> ""
func changeCase(input: String) -> String {
return input.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.joined()
}
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] ==> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// Given a non-empty array of integers, return the result of multiplying the values together in order.
// For example:
// [1, 2, 3, 4] ==> 1 * 2 * 3 * 4 = 24
func multiplyArray(array: [Int]) -> Int {
return array.reduce(1, { $0 * $1 })
}
// Your goal is to return multiplication table for number that is always an integer from 1 to 10.
// For example, a multiplication table (string) for number == 5 looks like below:
// 1 * 5 = 5
// 2 * 5 = 10
// 3 * 5 = 15
// 4 * 5 = 20
// 5 * 5 = 25
// 6 * 5 = 30
// 7 * 5 = 35
// 8 * 5 = 40
// 9 * 5 = 45
// 10 * 5 = 50
// P. S. You can use \n in string to jump to the next line.
func multiplicationTable(number: Int) -> String {
var result = ""
for i in 1...10 {
result += "\(i) * \(number) = \(i * number)\n"
}
return result
}
// Given an array of integers, find the one that appears an odd number of times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
func findOdd(array: [Int]) -> Int {
return array.filter { $0 % 2 == 1 }.first!
}
// Given a string, return a new string with the reversed order of characters.
// For example:
// "Hi There" ==> "eerht iH"
// "Hi" ==> "iH"
// "" ==> ""
func reverseString(input: String) -> String {
return input.reversed().join()
}
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] ==> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// Given a non-empty array of integers, return the result of multiplying the values together in order.
// For example:
// [1, 2, 3] ==> 6
func multiplyArray(array
return Double(a) * h / 2 // cannot convert value of type 'Int' to expected argument type 'Double'
return input.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.joined() // value of type 'String.Element' (aka 'Character') has no member 'toUpperCase'
return input.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.joined() // value of type 'String.Element' (aka 'Character') has no member 'toLowerCase'
return input.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.joined() // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
return input.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello") == "olleh"
func reverseString(_ string: String) -> String {
return string.reversed().join()
}
// Given a string, return a new string with the reversed order of characters.
// reverseString("hello")
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
func vowelFree(str: String) -> String {
return str.filter { !"aeiouAEIOU".contains(Character(c: $0)) }
}
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiouAEIOU".contains(Character(c: $0)) }
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func charCount(str: String, char: Character) -> Int {
return str.count(for: char)
}
// Given a string, return the number of times the character appears in the string.
// charCount("Hello", "l") == 2
func char
return Double(a) * h / 2 // cannot convert value of type 'Int' to expected argument type 'Double'
return str.filter { !"aeiouAEIOU".contains(Character(c: $0)) } // incorrect argument label in call (have 'c:', expected 'extendedGraphemeClusterLiteral:')
return str.count(for: char) // cannot call value of non-function type 'Int'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
func vowelFree(s: String) -> String {
var result = ""
for char in s {
if !isVowel(char) {
result += char
}
}
return result
}
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(s: String) -> String {
var result = ""
for char in s {
if !isVowel(char) {
result += char
}
}
return result
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
// countChar("Hello", "l") == 2
func countChar(s: String, c: Character) -> Int {
var count = 0
for char in s {
if char == c {
count += 1
}
}
return count
}
// Given a string, return the number of times the character appears in the string.
return Double(a) * h / 2 // cannot convert value of type 'Int' to expected argument type 'Double'
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
func stringTransformer(str: String) -> String {
var newStr = ""
for char in str {
if char == " " {
newStr += " "
} else if char.isUpper {
newStr += char.lowerCasedString
} else {
newStr += char.upperCasedString
}
}
return newStr.trimmingCharacters(in: .whitespace)
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HILlE"
// "" ==> ""
func stringTransformer(str: String) -> String {
var newStr = ""
for char in str {
if char == " " {
newStr += " "
} else if char.isUpper {
newStr += char.lowerCasedString
} else {
newStr += char.upperCasedString
}
}
return newStr.trimmingCharacters(in: .whitespace)
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HILlE"
// "" ==> ""
func stringTransformer(str: String) -> String {
var newStr = ""
for char in str {
if char == " " {
newStr += " "
} else if char.isUpper {
newStr += char.lowerCasedString
} else {
newStr += char.upperCasedString
}
}
return newStr.trimmingCharacters(in: .whitespace)
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HILlE"
// "" ==> ""
func stringTransformer(str: String) -> String {
var newStr = ""
for char in str {
if char == " " {
newStr += " "
} else if char.isUpper {
newStr += char.lowerCasedString
} else {
newStr += char.upperCasedString
}
}
return newStr.trimmingCharacters(in: .whitespace)
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HILlE"
// "" ==> ""
func stringTransformer(str: String) -> String {
var newStr = ""
for char in str {
if char == " " {
newStr += " "
} else if char.isUpper {
newStr += char.lowerCasedString
} else {
newStr += char.upperCasedString
}
}
return newStr.trimmingCharacters(in: .whitespace)
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
} else if char.isUpper { // value of type 'Character' has no member 'isUpper'
newStr += char.lowerCasedString // value of type 'Character' has no member 'lowerCasedString'
newStr += char.upperCasedString // value of type 'Character' has no member 'upperCasedString'
return newStr.trimmingCharacters(in: .whitespace) // type 'CharacterSet' has no member 'whitespace'
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// Given a string, return the string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(string: String) -> String {
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // cannot use mutating member on immutable value: 'string' is a 'let' constant
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // value of tuple type '()' has no member 'replace'
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // missing argument label 'with:' in call
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return a * h / 2
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".contains($0) }
}
// Given a string, return a new string with all the vowels removed.
// vowelFree("Hello") == "Hll"
func vowelFree(str: String) -> String {
return str.filter { !"aeiou".
return a * h / 2 // cannot convert return expression of type 'Int' to return type 'Double'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
func transform(s: String) -> String {
var transformed = ""
for char in s {
if char == " " {
transformed += " "
} else {
if char.isUpper {
transformed += char.lower
} else {
transformed += char.upper
}
}
}
return transformed
}
func sumOfMultiples(number: Int) -> Int {
var sum = 0
for i in 1..<number {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * h / 2
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HOLO"
// " Hello World " ==> "dLOw NSRE hLLO"
func transform(s: String) -> String {
var transformed = ""
for char in s {
if char == " " {
transformed += " "
} else {
if char.isUpper {
transformed += char.lower
} else {
transformed += char.upper
}
}
}
return transformed
}
// Given a number, find the sum of all the unique multiples of particular numbers up to but not including that number.
// If we list all the natural numbers below 30 that are multiples of 3 or 5, we get 3, 5, 6, 9, 10, 12 and 15.
// The sum of these multiples is 33.
// Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
// We will not be given a value less than 1.
func sumOfMultiples(number: Int) -> Int {
var sum = 0
for i in 1..<number {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HOLO"
// " Hello World " ==> "dLOw NSRE hLLO"
func transform(s: String) -> String {
var transformed = ""
for char in s {
if char == " " {
transformed += " "
} else {
if char.isUpper {
transformed += char.lower
} else {
transformed += char.upper
}
}
}
return transformed
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HOLO"
// " Hello World " ==> "dLOw NSRE hLLO"
func transform(s: String) -> String {
var transformed = ""
for char in s {
if char == " " {
transformed += " "
} else {
if char.isUpper {
transformed += char.lower
} else {
transformed += char.upper
}
}
}
return transformed
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NSRE HOLO"
// " Hello World " ==> "dLOw NSRE hLLO"
func transform(s: String
return Double(a) * h / 2 // cannot convert value of type 'Int' to expected argument type 'Double'
if char.isUpper { // value of type 'Character' has no member 'isUpper'
transformed += char.lower // value of type 'Character' has no member 'lower'
transformed += char.upper // value of type 'Character' has no member 'upper'
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
func alphabetical(s: String) -> String {
if s.isEmpty {
return ""
} else {
return String(s.characters.sorted())
}
}
func reverseAlphabetical(s: String) -> String {
if s.isEmpty {
return ""
} else {
return String(s.characters.reversed())
}
}
func alphabeticalAndCount(s: String) -> String {
if s.isEmpty {
return ""
} else {
var result = ""
var count = 1
for i in 1..<s.count {
if s[i] == s[i - 1] {
count += 1
} else {
result += String(s[i - 1]) + String(count)
count = 1
}
}
result += String(s[s.count - 1]) + String(count)
return result
}
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
// 11. Write a function that takes a string and returns a string with the letters in alphabetical order.
// Example:
// alphabetical("hello") == "ehllo"
// alphabetical("hello world") == "dehllloorw"
// alphabetical("edabit") == "abdeit"
// alphabetical("") == ""
// alphabetical("h") == "h"
// alphabetical("coding") == "codin"
// alphabetical("algorithm") == "aaalgort"
// alphabetical("z") == "z"
// alphabetical("zoo") == "ooz"
func alphabetical(s: String) -> String {
if s.isEmpty {
return ""
} else {
return String(s.characters.sorted())
}
}
// 12. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// Example:
// reverseAlphabetical("hello") == "olleh"
// reverseAlphabetical("hello world") == "dlrow olleh"
// reverseAlphabetical("edabit") == "tabide"
// reverseAlphabetical("") == ""
// reverseAlphabetical("h") == "h"
// reverseAlphabetical("coding") == "gniido"
// reverseAlphabetical("algorithm") == "gortlima"
// reverseAlphabetical("z") == "z"
// reverseAlphabetical("zoo") == "ooz"
func reverseAlphabetical(s: String) -> String {
if s.isEmpty {
return ""
} else {
return String(s.characters.reversed())
}
}
// 13. Write a function that takes a string and returns a string with the letters in alphabetical order and the number of times each letter appears.
// Example:
// alphabeticalAndCount("hello") == "e1l1o3h1"
// alphabeticalAndCount("hello world") == "d1e1l1o1r1l1w1o1r1"
// alphabeticalAndCount("edabit") == "a1b1d1e1t1"
// alphabeticalAndCount("") == ""
// alphabeticalAndCount("h") == "h1"
// alphabeticalAndCount("coding") == "c1d1i1n1g1o1"
// alphabeticalAndCount("algorithm") == "a1c1g1l1o1m1t1r1i1"
// alphabeticalAndCount("z") == "z1"
// alphabeticalAndCount("zoo") == "o1z2"
func alphabeticalAndCount(s: String) -> String {
if s.isEmpty {
return ""
} else {
var result = ""
var count = 1
for i in 1..<s.count {
if s[i] == s[i - 1] {
count += 1
} else {
result += String(s[i - 1]) + String(count)
count = 1
}
}
result += String(s[s.count - 1]) + String(count)
return result
}
}
// 14. Write a function that takes a string and returns a string with the letters in reverse alphabetical order and the number of times each letter appears.
// Example:
// reverseAlphabeticalAndCount("hello") == "e1l1o3h1"
// reverseAlphabeticalAndCount("hello world") == "d1e1l1o1r1l1w1
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return String(s.characters.sorted()) // 'characters' is unavailable: Please use String directly
return String(s.characters.reversed()) // 'characters' is unavailable: Please use String directly
if s[i] == s[i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += String(s[i - 1]) + String(count) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += String(s[s.count - 1]) + String(count) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0...n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3] + fib[i - 4]
}
}
return fib[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0...n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3] + fib[i - 4]
}
}
return fib[n]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
// Fatal error: Index out of range
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0..<4 {
fib[i] = i
}
for i in 4..<n {
fib[i % 4] = fib[0] + fib[1] + fib[2] + fib[3]
}
return fib[n % 4]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0..<4 {
fib[i] = i
}
for i in 4..<n {
fib[i % 4] = fib[0] + fib[1] + fib[2] + fib[3]
}
return fib[n % 4]
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var fibs = [0, 0, 0, 0]
for i in 0...3 {
fibs[i] = 1
}
for _ in 0...n - 4 {
var sum = 0
for i in 0...3 {
sum += fibs[i]
}
fibs[0] = fibs[1]
fibs[1] = fibs[2]
fibs[2] = fibs[3]
fibs[3] = sum
}
return fibs[3]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var fibs = [0, 0, 0, 0]
for i in 0...3 {
fibs[i] = 1
}
for _ in 0...n - 4 {
var sum = 0
for i in 0...3 {
sum += fibs[i]
}
fibs[0] = fibs[1]
fibs[1] = fibs[2]
fibs[2] = fibs[3]
fibs[3] = sum
}
return fibs[3]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0...n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i-1] + fib[i-2] + fib[i-3] + fib[i-4]
}
}
return fib[n]
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0...n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i-1] + fib[i-2] + fib[i-3] + fib[i-4]
}
}
return fib[n]
}
// 10. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are a, e, i, o, u.
// If the string doesn't consist of vowels, return the string unchanged.
// removeVowels("The quick brown fox jumps over the lazy dog") == "Th qck brwn fx jmps vr th lzy dg"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 11. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are a, e, i, o, u.
// If the string doesn't consist of vowels, return the string unchanged.
// removeVowels("The quick brown fox jumps over the lazy dog") == "Th qck brwn fx jmps vr th lzy dg"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 12. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are a, e, i, o, u.
// If the string doesn't consist of vowels, return the string unchanged.
// removeVowels("The quick brown fox jumps over the lazy dog") == "Th qck brwn fx jmps vr th lzy dg"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 13. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are a, e, i, o, u.
// If the string doesn't consist of vowels, return the string unchanged.
// removeVowels("The quick brown fox jumps over the lazy dog") == "Th qck brwn fx jmps vr th lzy dg"
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 14. Write a function that takes a string and returns a new string with all the vowels removed.
// The vowels are a, e, i, o, u.
// If the string doesn't consist of vowels, return the string unchanged.
// removeVowels("The quick brown fox jumps over the lazy dog") == "Th qck brwn fx jmps vr th lzy dg"
func removeVowels(input: String) -> String {
var result = "
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fib4(n: Int) -> Int {
return 0
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
return 0
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i + 1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
func containsDuplicate(nums: [Int]) -> Bool {
var set = Set<Int>()
for num in nums {
if set.contains(num) {
return true
} else {
set.insert(num)
}
}
return false
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4)
}
}
// 2. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i + 1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
// 4. Given an array of integers, find if the array contains any duplicates.
// Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
// Example 1:
// Input: [1,2,3,1]
// Output: true
// Example 2:
// Input: [1,2,3,4]
// Output: false
// Example 3:
// Input: [1,1,1,3,3,4,3,2,4,2]
// Output: true
func containsDuplicate(nums: [Int]) -> Bool {
var set = Set<Int>()
for num in nums {
if set.contains(num) {
return true
} else {
set.insert(num)
}
}
return false
}
// 5. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// 6. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// 7. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// 8. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11,
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
return fib4(n - 1) + fib4(n - 2) + fib4(n - 3) + fib4(n - 4) // missing argument label 'n:' in call
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0..<n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3] + fib[i - 4]
}
}
return fib[n]
}
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func wordCount(string: String) -> Int {
var count = 0
var isWord = false
for char in string {
if char == " " {
isWord = false
} else if !isWord {
isWord = true
count += 1
}
}
return count
}
func consonantCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == " " {
continue
} else {
count += 1
}
}
return count
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
var fib = [0, 0, 0, 0]
for i in 0..<n {
if i == 0 {
fib[i] = 0
} else if i == 1 {
fib[i] = 0
} else if i == 2 {
fib[i] = 2
} else if i == 3 {
fib[i] = 0
} else {
fib[i] = fib[i - 1] + fib[i - 2] + fib[i - 3] + fib[i - 4]
}
}
return fib[n]
}
// 10. Write a function that takes a string and returns the number of vowels in the string.
// You should treat a letter's case as alphabetical when determining the number of vowels, and you should treat the letter y as a vowel.
// Assume the input will always be a string.
// vowelCount("Crab up!") == 5
// vowelCount("abracadabra") == 5
// vowelCount("rhythm repeating") == 2
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 11. Write a function that takes a string and returns the number of words in the string.
// You should treat a letter's case as alphabetical when determining the number of words, and you should treat the letter y as a word.
// Assume the input will always be a string.
// wordCount("Crab up!") == 1
// wordCount("abracadabra") == 6
// wordCount("rhythm repeating") == 2
func wordCount(string: String) -> Int {
var count = 0
var isWord = false
for char in string {
if char == " " {
isWord = false
} else if !isWord {
isWord = true
count += 1
}
}
return count
}
// 12. Write a function that takes a string and returns the number of consonants in the string.
// You should treat a letter's case as alphabetical when determining the number of consonants, and you should treat the letter y as a consonant.
// Assume the input will always be a string.
// consonantCount("Crab up!") == 3
// consonantCount("abracadabra") == 5
// consonantCount("rhythm repeating") == 3
func consonantCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == " " {
continue
} else {
count += 1
}
}
return count
}
// 13. Write a function that takes a string and returns the number of consonants in the string.
// You should treat a letter's case as alphabetical when determining the number of consonants, and you should treat the letter y as a consonant.
// Assume the input will always be a string.
// consonantCount("Crab up!") == 3
// consonantCount("abracadabra") == 5
// consonantCount("rhythm repeating") == 3
func consonantCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == " " {
continue
} else {
count += 1
}
}
return count
}
// 14. Write a function that takes a string and returns the number of consonants in the string.
// You should treat a letter's case as alphabetical when determining the number of conson
// Fatal error: Index out of range
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
var fib4 = [0, 0, 2, 0]
for i in 4...n {
fib4.append(fib4[i-1] + fib4[i-2] + fib4[i-3] + fib4[i-4])
}
return fib4[n]
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
return (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return sorted[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
? (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
? (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
}
print(median([3, 1, 2, 4, 5]))
print(median([-10, 4, 6, 1000, 10, 20]))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let l = l.sorted()
let middle = l.count / 2
return l.count % 2 == 0 ? (l[middle - 1] + l[middle]) / 2 : l[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let l = l.sorted()
let middle = l.count / 2
return l.count % 2 == 0 ? (l[middle - 1] + l[middle]) / 2 : l[middle]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
return l.count % 2 == 0 ? (l[middle - 1] + l[middle]) / 2 : l[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let count = l.count
if count == 0 {
return 0
}
if count % 2 == 0 {
return (l[count / 2 - 1] + l[count / 2]) / 2
} else {
return l[count / 2]
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let count = l.count
if count == 0 {
return 0
}
if count % 2 == 0 {
return (l[count / 2 - 1] + l[count / 2]) / 2
} else {
return l[count / 2]
}
}
// -----------------------------------------------------------------------------
// MARK: - 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// MARK: - 1.1.14
// -----------------------------------------------------------------------------
// ------------------------------------
return (l[count / 2 - 1] + l[count / 2]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return l[count / 2] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
return (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return sorted[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
if sorted.count % 2 == 0 {
return (sorted[middle - 1] + sorted[middle]) / 2
} else {
return sorted[middle]
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
return sorted[middle] // cannot convert return expression of type 'Int' to return type 'Double'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let middle = sorted.count / 2
return sorted.count % 2 == 0
? (sorted[middle - 1] + sorted[middle]) / 2
: sorted[middle]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
? (sorted[middle - 1] + sorted[middle]) / 2 // cannot convert return expression of type 'Int' to return type 'Double'
func isPalindrome(text: String) -> Bool {
let reversed = String(text.reversed())
return text == reversed
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let reversed = String(text.reversed())
return text == reversed
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as a parameter and returns the number
// of vowels in the string.
//
// For example, the number of vowels in "abracadabra" is 5.
//
// Don't count y as a vowel.
//
// Hint: Use the characterSet property of the String class.
//
// isVowel(character: "a") == true
// isVowel(character: "b") == false
// isVowel(character: "y") == false
// isVowel(character: "z") == false
// isVowel(character: "Y") == false
// isVowel(character: "") == false
// isVowel(character: " ") == false
// isVowel(character: "1") == false
// isVowel(character: "2") == false
// isVowel(character: "3") == false
// isVowel(character: "4") == false
// isVowel(character: "5") == false
// isVowel(character: "6") == false
// isVowel(character: "7") == false
// isVowel(character: "8") == false
// isVowel(character: "9") == false
// isVowel(character: "0") == false
// isVowel(character: "a") == true
// isVowel(character: "b") == false
// isVowel(character: "c") == false
// isVowel(character: "d") == false
// isVowel(character: "e") == true
// isVowel(character: "f") == false
// isVowel(character: "g") == false
// isVowel(character: "h") == false
// isVowel(character: "i") == true
// isVowel(character: "j") == false
// isVowel(character: "k") == false
// isVowel(character: "l") == false
// isVowel(character: "m") == false
// isVowel(character: "n") == true
// isVowel(character: "o") == true
// isVowel(character: "p") == false
// isVowel(character: "q") == false
// isVowel(character: "r") == true
// isVowel(character: "s") == true
// isVowel(character: "t") == true
// isVowel(character: "u") == true
// isVowel(character: "v") == false
// isVowel(character: "w") == false
// isVowel(character: "x") == false
// isVowel(character: "y") == false
// isVowel(character: "z") == false
// isVowel(character: "A") == true
// isVowel(character: "B") == false
// isVowel(character: "C") == false
// isVowel(character: "D") == false
// isVowel(character: "E") == true
// isVowel(character: "F") == false
// isVowel(character: "G") == false
// isVowel(character: "H") == false
// isVowel(character: "I") == true
// isVowel(character: "J") == false
// isVowel(character: "K") == false
// isVowel(character: "L") == false
// isVowel(character: "M") == false
// isVowel(character: "N") == true
// isVowel(character: "O") == true
// isVowel(character: "P") == false
// isVowel
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// -----------------------------------------------------------------------------
// 1.7
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text.reversed() == text
}
// ------------------------------------------------------
return text.reversed() == text // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'String'
func isPalindrome(text: String) -> Bool {
var left = 0
var right = text.length - 1
while left < right {
if text[left] != text[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
var left = 0
var right = text.length - 1
while left < right {
if text[left] != text[right] {
return false
}
left += 1
right -= 1
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
var right = text.length - 1 // value of type 'String' has no member 'length'
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of vowels
// in the string.
//
// vowels("aeiou") == 5
// vowels("bcdfghjklmnpqrstvwxyz") == 0
// vowels("") == 0
// vowels(" ") == 0
// vowels("a") == 1
// vowels("aeioua") == 5
// vowels("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// ------------
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the string with all
// lowercase letters reversed.
//
// lowercaseLettersReversed(text: "") == ""
// lowercaseLettersReversed(text: "a") == "a"
// lowercaseLettersReversed(text: "A") == "a"
// lowercaseLettersReversed(text: "aBc") == "cba"
// lowercaseLettersReversed(text: "Abc") == "cba"
// lowercaseLettersReversed(text: "aBcD") == "dcba"
// lowercaseLettersReversed(text: "AbcD") == "dcba"
// lowercaseLettersReversed(text: "aBcDeFgHiJkLmNoPqRsTuVwXyZ") == "zyXwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the string with all
// uppercase letters reversed.
//
// uppercaseLettersReversed(text: "") == ""
// uppercaseLettersReversed(text: "a") == "A"
// uppercaseLettersReversed(text: "A") == "a"
// uppercaseLettersReversed(text: "aBc") == "cBa"
// uppercaseLettersReversed(text: "aBcD") == "dcBa"
// uppercaseLettersReversed(text: "AbcD") == "dcBa"
// uppercaseLettersReversed(text: "aBcDeFgHiJkLmNoPqRsTuVwXyZ") == "zyXwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the string with all
// lowercase letters replaced by uppercase letters and all uppercase letters
// replaced by lowercase letters.
//
// swapCase(text: "") == ""
// swapCase(text: "a") == "A"
// swapCase(text: "A") == "a"
// swapCase(text: "aBc") == "cBa"
// swapCase(text: "aBcD") == "dcBa"
// swapCase(text: "AbcD") == "dcBa"
// swapCase(text: "aBcDeFgHiJkLmNoPqRsTuVwXyZ") == "zyXwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the string with all
// lowercase letters replaced by uppercase letters and all uppercase letters
// replaced by lowercase letters.
//
// swapCase(text: "") == ""
// swapCase(text: "a") == "A"
// swapCase(text: "A") == "a"
// swapCase(text: "aBc") == "cBa"
// swapCase(text: "aBcD") == "dcBa"
// swapCase(text: "AbcD") == "dcBa"
// swapCase(text: "aBcDeFgHiJkLmNoP
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.16
// ------------------------------------------------------------------------
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.2
//
// Given a string, compute recursively (no loops) a new string where all the
// lowercase 'x' chars have been changed to 'y' chars.
//
// xChangeY("") == ""
// xChangeY("x") == "y"
// xChangeY("xx") == "yy"
// xChangeY("xy") == "yx"
// xChangeY("xyx") == "yxy"
// xChangeY("xyxxy") == "yxyxy"
// xChangeY("xyxxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxy
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
return text == String(text.reversed())
}
// ------------
func isPalindrome(text: String) -> Bool {
let reversed = String(text.reversed())
return text == reversed
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let reversed = String(text.reversed())
return text == reversed
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
// pow
//
//
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
public struct BigInt {
public var digits: [Int]
public var sign: Int
public var isZero: Bool {
return digits.count == 1 && digits[0] == 0
}
public var isNegative: Bool {
return sign == -1
}
public var isPositive: Bool {
return sign == 1
}
public var isEven: Bool {
return digits.count % 2 == 0
}
public var isOdd: Bool {
return digits.count % 2 == 1
}
public var isOne: Bool {
return digits.count == 1 && digits[0] == 1
}
public var isTwo: Bool {
return digits.count == 1 && digits[0] == 2
}
public var isThree: Bool {
return digits.count == 1 && digits[0] == 3
}
public var isFour: Bool {
return digits.count == 1 && digits[0] == 4
}
public var isFive: Bool {
return digits.count == 1 && digits[0] == 5
}
public var isSix: Bool {
return digits.count == 1 && digits[0] == 6
}
public var isSeven: Bool {
return digits.count == 1 && digits[0] == 7
}
public var isEight: Bool {
return digits.count == 1 && digits[0] == 8
}
public var isNine: Bool {
return digits.count == 1 && digits[0] == 9
}
public var isTen: Bool {
return digits.count == 1 && digits[0] == 10
}
public var isEleven: Bool {
return digits.count == 1 && digits[0] == 11
}
public var isTwelve: Bool {
return digits.count == 1 && digits[0] == 12
}
public var isThirteen: Bool {
return digits.count == 1 && digits[0] == 13
}
public var isFourteen: Bool {
return digits.count == 1 && digits[0] == 14
}
public var isFifteen: Bool {
return digits.count == 1 && digits[0] == 15
}
public var isSixteen: Bool {
return digits.count == 1 && digits[0] == 16
}
public var isSeventeen: Bool {
return digits.count == 1 && digits[0] == 17
}
public var isEighteen: Bool {
return digits.count == 1 && digits[0] == 18
}
public var isNineteen: Bool {
return digits.count == 1 && digits[0] == 19
}
public var isTwenty: Bool {
return digits.count == 1 && digits[0] == 20
}
public var isThirty: Bool {
return digits.count == 1 && digits[0] == 30
}
public var isForty: Bool {
return digits.count == 1 && digits[0] == 40
}
public var isFifty: Bool {
return digits.count == 1 && digits[0] == 50
}
public var isSixty: Bool {
return digits.count == 1 &&
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
let pow = powmod(n, p - 2, p)
return pow % p
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
let pow = powmod(n, p - 2, p)
return pow % p
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
let pow = powmod(n, p - 2, p) // cannot find 'powmod' in scope
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
struct Solution {
var result: Int
}
func main() {
let input = readInput()
let solution = Solution(result: 0)
solve(input: input, solution: &solution)
print(solution.result)
}
func readInput() -> Int {
let input = readLines()
return Int(input[0])!
}
func solve(input: Int, solution: inout Solution) {
solution.result = modp(n: input, p: 101)
}
func readLines() -> [String] {
let lines = readInput()
return lines.split(separator: "\n").map { $0 }
}
func readInput() -> String {
let file = open("input.txt")
let input = read(from: file)
close(file)
return input
}
func print(input: Int) {
print(input)
}
func print(input: [Int]) {
print(input.map { $0 }.map { "\($0)" }.join(separator: ", "))
}
func print(input: [String]) {
print(input.map { $0 }.map { "\($0)" }.join(separator: ", "))
}
func print(input: [Int], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: [String], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: Int, separator: String) {
print(input, separator: separator)
}
func print(input: Int, separator: String, terminator: String) {
print(input, separator: separator, terminator: terminator)
}
func print(input: [Int], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator)
}
func print(input: [String], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Solution {
var result: Int
}
func main() {
let input = readInput()
let solution = Solution(result: 0)
solve(input: input, solution: &solution)
print(solution.result)
}
func readInput() -> Int {
let input = readLines()
return Int(input[0])!
}
func solve(input: Int, solution: inout Solution) {
solution.result = modp(n: input, p: 101)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func readLines() -> [String] {
let lines = readInput()
return lines.split(separator: "\n").map { $0 }
}
func readInput() -> String {
let file = open("input.txt")
let input = read(from: file)
close(file)
return input
}
func print(input: Int) {
print(input)
}
func print(input: [Int]) {
print(input.map { $0 }.map { "\($0)" }.join(separator: ", "))
}
func print(input: [String]) {
print(input.map { $0 }.map { "\($0)" }.join(separator: ", "))
}
func print(input: [Int], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: [String], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: Int, separator: String) {
print(input, separator: separator)
}
func print(input: [Int], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: [String], separator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator))
}
func print(input: Int, separator: String, terminator: String) {
print(input, separator: separator, terminator: terminator)
}
func print(input: [Int], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator)
}
func print(input: [String], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator)
}
func print(input: Int, separator: String, terminator: String) {
print(input, separator: separator, terminator: terminator)
}
func print(input: [Int], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator)
}
func print(input: [String], separator: String, terminator: String) {
print(input.map { $0 }.map { "\($0)" }.
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
let input = readInput() // ambiguous use of 'readInput()'
solve(input: input, solution: &solution) // cannot pass immutable value as inout argument: 'solution' is a 'let' constant
let lines = readInput() // ambiguous use of 'readInput()'
let file = open("input.txt") // missing argument for parameter #2 in call
let input = read(from: file) // missing arguments for parameters #2, #3 in call
let input = read(from: file) // extraneous argument label 'from:' in call
print(input.map { $0 }.map { "\($0)" }.join(separator: ", ")) // value of type '[String]' has no member 'join'
print(input.map { $0 }.map { "\($0)" }.join(separator: ", ")) // value of type '[String]' has no member 'join'
print(input.map { $0 }.map { "\($0)" }.join(separator: separator)) // value of type '[String]' has no member 'join'
print(input.map { $0 }.map { "\($0)" }.join(separator: separator)) // value of type '[String]' has no member 'join'
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator) // value of type '[String]' has no member 'join'
print(input.map { $0 }.map { "\($0)" }.join(separator: separator), terminator: terminator) // value of type '[String]' has no member 'join'
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return pow(2, n, p)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
return pow(2, n, p) // cannot convert return expression of type 'Decimal' to return type 'Int'
return pow(2, n, p) // extra argument in call
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// vowels removed.
//
// remove_vowels("") == ""
// remove_vowels("abcdef") == "bcdf"
// remove_vowels("aaaaa") == ""
// remove_vowels("aaBAA") == "B"
// remove_vowels("zbcd") == "zbcd"
//
// You may assume the input will always be a string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// vowels removed.
//
// remove_vowels("") == ""
// remove_vowels("abcdef") == "bcdf"
// remove_vowels("aaaaa") == ""
// remove_vowels("aaBAA") == "B"
// remove_vowels("zbcd") == "zbcd"
//
// You may assume the input will always be a string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// vowels removed.
//
// remove_vowels("") == ""
// remove_vowels("abcdef") == "bcdf"
// remove_vowels("aaaaa") == ""
// remove_vowels("aaBAA") == "B"
// remove_vowels("zbcd") == "zbcd"
//
// You may assume the input will always be a string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// vowels removed.
//
// remove_vowels("") == ""
// remove_vowels("abcdef") == "bcdf"
// remove_vowels("aaaaa") == ""
// remove_vowels("aaBAA") == "B"
// remove_vowels("zbcd") == "zbcd"
//
// You may assume the input will always be a string.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// vowels removed.
//
// remove_vowels("") == ""
// remove_vowels("abcdef") == "bcdf"
// remove_vowels("aaaaa") == ""
// remove_vowels("aaBAA") == "B"
// remove_vowels("zbcd") == "zbcd"
//
// You may assume the input will always be a string.
// ---------------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func makeTitle(text: String) -> String {
var result = ""
var words = text.split(" ")
for word in words {
result += word.capitalized
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// makeTitle("the quick brown fox") == "The Quick Brown Fox"
// makeTitle("t") == "T"
// makeTitle("") == ""
// makeTitle("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
func makeTitle(text: String) -> String {
var result = ""
var words = text.split(" ")
for word in words {
result += word.capitalized
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// makeTitle("the quick brown fox") == "The Quick Brown Fox"
// makeTitle("t") == "T"
// makeTitle("") == ""
// makeTitle("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
func makeTitle(text: String) -> String {
var result = ""
var words = text.split(" ")
for word in words {
result += word.capitalized
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// makeTitle("the quick brown fox") == "The Quick Brown Fox"
// makeTitle("t") == "T"
// makeTitle("") == ""
// makeTitle("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
func makeTitle(text: String) -> String {
var result = ""
var words = text.split(" ")
for word in words {
result += word.capitalized
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// makeTitle("the quick brown fox") == "The Quick Brown Fox"
// makeTitle("t") == "T"
// makeTitle("") == ""
// makeTitle("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
func makeTitle(text: String) -> String {
var result = ""
var words = text.split(" ")
for word in words {
result += word.capitalized
}
return result
}
// ------------------------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
var words = text.split(" ") // no exact matches in call to instance method 'split'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a string with the first
// character of each word capitalized.
//
// capitalizeFirst("") == ""
// capitalizeFirst("abc def") == "Abc Def"
// capitalizeFirst("cat dog") == "Cat Dog"
// capitalizeFirst("cat dog dog") == "Cat Dog Dog"
// capitalizeFirst("cat dog dog cat") == "Cat Dog Dog Cat"
// capitalizeFirst("cat dog dog cat dog") == "Cat Dog Dog Cat Dog"
// capitalizeFirst("cat dog dog cat dog dog") == "Cat Dog Dog Cat Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog dog") == "Cat Dog Dog Cat Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog Dog"
// capitalizeFirst("cat dog dog cat dog dog dog dog dog dog dog dog dog dog dog dog dog
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in text {
if !vowels.contains(char) {
result += char
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in text {
if !vowels.contains(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.16
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.17
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.18
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.19
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.20
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.21
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.22
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.23
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.24
// -----------------------------------------------------------------------------
// ---------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func capitalizeFirstLetter(text: String) -> String {
return String(text.first!.uppercased) + text.substring(1)
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalizeFirstLetter("") == ""
// capitalizeFirstLetter("abc") == "Abc"
// capitalizeFirstLetter("aBc") == "ABc"
// capitalizeFirstLetter("aBC") == "ABC"
// capitalizeFirstLetter("aBCd") == "ABCd"
func capitalizeFirstLetter(text: String) -> String {
return String(text.first!.uppercased) + text.substring(1)
}
// 3. Write a function that takes a string and returns a string with the first letter of each word capitalized.
// capitalizeFirstLetterOfEachWord("") == ""
// capitalizeFirstLetterOfEachWord("abc") == "Abc"
// capitalizeFirstLetterOfEachWord("aBc") == "ABc"
// capitalizeFirstLetterOfEachWord("aBC") == "ABC"
// capitalizeFirstLetterOfEachWord("aBCd") == "ABCd"
// capitalizeFirstLetterOfEachWord("aBCdef") == "ABCdef"
// capitalizeFirstLetterOfEachWord("aBCdefg") == "ABCdefg"
// capitalizeFirstLetterOfEachWord("aBCdefgh") == "ABCdefgh"
// capitalizeFirstLetterOfEachWord("aBCdefghi") == "ABCdefghi"
// capitalizeFirstLetterOfEachWord("aBCdefghij") == "ABCdefghij"
// capitalizeFirstLetterOfEachWord("aBCdefghijk") == "ABCdefghijk"
// capitalizeFirstLetterOfEachWord("aBCdefghijkl") == "ABCdefghijkl"
// capitalizeFirstLetterOfEachWord("aBCdefghijklm") == "ABCdefghijklm"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmn") == "ABCdefghijklmn"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABCdefghijklmno"
// capitalizeFirstLetterOfEachWord("aBCdefghijklmno") == "ABC
result += char // cannot convert value of type 'Character' to expected argument type 'String'
return String(text.first!.uppercased) + text.substring(1) // type '() -> String' cannot conform to 'LosslessStringConvertible'
return String(text.first!.uppercased) + text.substring(1) // no exact matches in call to instance method 'substring'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalizeFirstLetter(text: "") == ""
// capitalizeFirstLetter(text: "abcdef") == "Abcdef"
// capitalizeFirstLetter(text: "aBcDeF") == "ABcdef"
// capitalizeFirstLetter(text: "Abcdef") == "Abcdef"
// capitalizeFirstLetter(text: "aBcdef") == "ABcdef"
// capitalizeFirstLetter(text: "Abcdefg") == "Abcdefg"
// capitalizeFirstLetter(text: "AbcdefG") == "AbcdefG"
// capitalizeFirstLetter(text: "AbcdefGh") == "AbcdefGh"
// capitalizeFirstLetter(text: "AbcdefGhI") == "AbcdefGhI"
// capitalizeFirstLetter(text: "AbcdefGhIj") == "AbcdefGhIj"
// capitalizeFirstLetter(text: "AbcdefGhIjK") == "AbcdefGhIjK"
// capitalizeFirstLetter(text: "AbcdefGhIjKl") == "AbcdefGhIjKl"
// capitalizeFirstLetter(text: "AbcdefGhIjKlm") == "AbcdefGhIjKlm"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmn") == "AbcdefGhIjKlmn"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnop") == "AbcdefGhIjKlmnop"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQ") == "AbcdefGhIjKlmnopQ"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQr") == "AbcdefGhIjKlmnopQr"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrs") == "AbcdefGhIjKlmnopQrs"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsT") == "AbcdefGhIjKlmnopQrsT"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTu") == "AbcdefGhIjKlmnopQrsTu"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuv") == "AbcdefGhIjKlmnopQrsTuv"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvW") == "AbcdefGhIjKlmnopQrsTuvW"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvWX") == "AbcdefGhIjKlmnopQrsTuvWX"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvWXY") == "AbcdefGhIjKlmnopQrsTuvWXY"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvWXYZ") == "AbcdefGhIjKlmnopQrsTuvWXYZ"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvWXYZa") == "AbcdefGhIjKlmnopQrsTuvWXYZa"
// capitalizeFirstLetter(text: "AbcdefGhIjKlmnopQrsTuvW
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func capitalizeFirstLetter(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased() + text.dropFirst())
}
func lowercase(text: String) -> String {
return text.lowercased
}
func uppercase(text: String) -> String {
return text.uppercased
}
func swapCase(text: String) -> String {
return text.swapCase
}
func reverse(text: String) -> String {
return String(text.reversed)
}
func capitalizeFirstLetter(text: String) -> String {
return String(text.capitalized)
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalizeFirstLetter("") == ""
// capitalizeFirstLetter("a") == "A"
// capitalizeFirstLetter("hello") == "Hello"
// capitalizeFirstLetter("hElLo") == "Hello"
// capitalizeFirstLetter("hElLo world") == "Hello world"
func capitalizeFirstLetter(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased() + text.dropFirst())
}
// 3. Write a function that takes a string and returns a string with all the letters converted to lowercase.
// lowercase("") == ""
// lowercase("A") == "a"
// lowercase("Hello") == "hello"
// lowercase("hElLo") == "hello"
// lowercase("hElLo world") == "hello world"
func lowercase(text: String) -> String {
return text.lowercased
}
// 4. Write a function that takes a string and returns a string with all the letters converted to uppercase.
// uppercase("") == ""
// uppercase("A") == "A"
// uppercase("Hello") == "HELLO"
// uppercase("hElLo") == "HELLO"
// uppercase("hElLo world") == "HELLO WORLD"
func uppercase(text: String) -> String {
return text.uppercased
}
// 5. Write a function that takes a string and returns a string with all the letters converted to uppercase.
// swapCase("") == ""
// swapCase("A") == "a"
// swapCase("Hello") == "hElLo"
// swapCase("hElLo") == "HELLO"
// swapCase("hElLo world") == "hElLo WORLD"
func swapCase(text: String) -> String {
return text.swapCase
}
// 6. Write a function that takes a string and returns a string with all the letters converted to uppercase.
// reverse("") == ""
// reverse("a") == "a"
// reverse("Hello") == "olleH"
// reverse("hElLo") == "olleH"
// reverse("hElLo world") == "dlrow olleH"
func reverse(text: String) -> String {
return String(text.reversed)
}
// 7. Write a function that takes a string and returns a string with all the letters converted to uppercase.
// capitalizeFirstLetter("") == ""
// capitalizeFirstLetter("a") == "A"
// capitalizeFirstLetter("hello") == "Hello"
// capitalizeFirstLetter("hElLo") == "Hello"
// capitalizeFirstLetter("hElLo world") == "Hello world"
// capitalizeFirstLetter("hElLo world hello") == "Hello world hello"
func capitalizeFirstLetter(text: String) -> String {
return String(text.capitalized)
}
// 8. Write a function that takes a string and returns a string with all the letters converted to uppercase.
// capitalizeFirstLetter("") == ""
// capitalizeFirstLetter("a") == "A"
// capitalizeFirstLetter("hello") == "Hello"
// capitalizeFirstLetter("hElLo") == "Hello"
// capitalizeFirstLetter("hElLo world") == "Hello world"
// capitalizeFirstLetter("hElLo world hello") == "Hello world hello"
// capitalizeFirstLetter("hElLo world hello world") == "Hello world hello world"
func capitalizeFirstLetter(text: String) -> String
result += char // cannot convert value of type 'Character' to expected argument type 'String'
return text.lowercased // function produces expected type 'String'; did you mean to call it with '()'?
return text.uppercased // function produces expected type 'String'; did you mean to call it with '()'?
return text.swapCase // value of type 'String' has no member 'swapCase'
return String(text.reversed) // no exact matches in call to initializer
func capitalizeFirstLetter(text: String) -> String { // invalid redeclaration of 'capitalizeFirstLetter(text:)'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// Task 2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Task 2.13
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func capitalizeFirstLetter(text: String) -> String {
return String(text.first!.uppercaseString) + text.substring(1)
}
func reverseLetters(text: String) -> String {
return String(text.reversed())
}
func reverseWords(text: String) -> String {
return String(text.split(" ").reversed())
}
func alphabetPosition(text: String) -> String {
var result = ""
for char in text {
if char.isAlpha {
result += String(char.asciiValue - 96) + " "
}
}
return result.trim()
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalizeFirstLetter(text: "") == ""
// capitalizeFirstLetter(text: "abcdef") == "Abcdef"
// capitalizeFirstLetter(text: "aaaaa") == "Aaaaa"
// capitalizeFirstLetter(text: "aaBAA") == "AaBAA"
// capitalizeFirstLetter(text: "zbcd") == "Zbcd"
func capitalizeFirstLetter(text: String) -> String {
return String(text.first!.uppercaseString) + text.substring(1)
}
// 3. Write a function that takes a string and returns a string with all the letters reversed.
// reverseLetters(text: "") == ""
// reverseLetters(text: "abcdef") == "fedcba"
// reverseLetters(text: "aaaaa") == "aaaaa"
// reverseLetters(text: "aaBAA") == "aAAb"
// reverseLetters(text: "zbcd") == "dczb"
func reverseLetters(text: String) -> String {
return String(text.reversed())
}
// 4. Write a function that takes a string and returns a string with all the words reversed.
// reverseWords(text: "") == ""
// reverseWords(text: "abc def") == "def abc"
// reverseWords(text: "aaaaa") == "aaaaa"
// reverseWords(text: "aaBAA") == "BAAaa"
// reverseWords(text: "zbcd") == "dczb"
func reverseWords(text: String) -> String {
return String(text.split(" ").reversed())
}
// 5. Write a function that takes a string and returns a string with all the letters replaced by their position in the alphabet.
// alphabetPosition(text: "") == ""
// alphabetPosition(text: "abcdef") == "1 2 3 4 5 6"
// alphabetPosition(text: "aaaaa") == "1 1 1 1 1"
// alphabetPosition(text: "aaBAA") == "1 2 3 1 2"
// alphabetPosition(text: "zbcd") == "2 3 4 5"
func alphabetPosition(text: String) -> String {
var result = ""
for char in text {
if char.isAlpha {
result += String(char.asciiValue - 96) + " "
}
}
return result.trim()
}
// 6. Write a function that takes a string and returns a string with all the letters replaced by their position in the alphabet.
// alphabetPosition(text: "") == ""
// alphabetPosition(text: "abcdef") == "1 2 3 4 5 6"
// alphabetPosition(text: "aaaaa") == "1 1 1 1 1"
// alphabetPosition(text: "aaBAA") == "1 2 3 1 2"
// alphabetPosition(text: "zbcd") == "2 3 4 5"
func alphabetPosition(text: String) -> String {
var result = ""
for char in text {
if char.isAlpha {
result += String(char.asciiValue - 96) + " "
}
}
return result.trim()
}
// 7. Write a function that takes a string and returns a string with all the letters replaced by their position in the alphabet.
// alphabetPosition(text: "") == ""
// alphabetPosition(text: "abcdef") == "1 2 3 4 5 6"
// alphabetPosition(text: "aaaaa") == "1 1 1 1 1"
// alphabetPosition(text: "aaBAA") == "
result += char // cannot convert value of type 'Character' to expected argument type 'String'
return String(text.first!.uppercaseString) + text.substring(1) // value of type 'String.Element' (aka 'Character') has no member 'uppercaseString'
return String(text.first!.uppercaseString) + text.substring(1) // no exact matches in call to instance method 'substring'
return String(text.split(" ").reversed()) // no exact matches in call to instance method 'split'
return String(text.split(" ").reversed()) // initializer 'init(_:)' requires the types 'ReversedCollection<[ArraySlice<String.Element>]>.Element' (aka 'ArraySlice<Character>') and 'Character' be equivalent
if char.isAlpha { // value of type 'Character' has no member 'isAlpha'
result += String(char.asciiValue - 96) + " " // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
return result.trim() // value of type 'String' has no member 'trim'
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func capitalizeFirstLetter(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1)
}
func capitalizeFirstAndLastLetters(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased)
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalizeFirstLetter is a function that takes string and returns string with the first letter capitalized.
// capitalizeFirstLetter("") == ""
// capitalizeFirstLetter("a") == "A"
// capitalizeFirstLetter("hello") == "Hello"
// capitalizeFirstLetter("aBCdef") == "ABCdef"
func capitalizeFirstLetter(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1)
}
// 3. Write a function that takes a string and returns a string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters is a function that takes string and returns string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters("") == ""
// capitalizeFirstAndLastLetters("a") == "A"
// capitalizeFirstAndLastLetters("hello") == "Hello"
// capitalizeFirstAndLastLetters("aBCdef") == "ABCdef"
// capitalizeFirstAndLastLetters("aBCdefg") == "ABCdefG"
func capitalizeFirstAndLastLetters(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased)
}
// 4. Write a function that takes a string and returns a string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters is a function that takes string and returns string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters("") == ""
// capitalizeFirstAndLastLetters("a") == "A"
// capitalizeFirstAndLastLetters("hello") == "Hello"
// capitalizeFirstAndLastLetters("aBCdef") == "ABCdef"
// capitalizeFirstAndLastLetters("aBCdefg") == "ABCdefG"
func capitalizeFirstAndLastLetters(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased)
}
// 5. Write a function that takes a string and returns a string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters is a function that takes string and returns string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters("") == ""
// capitalizeFirstAndLastLetters("a") == "A"
// capitalizeFirstAndLastLetters("hello") == "Hello"
// capitalizeFirstAndLastLetters("aBCdef") == "ABCdef"
// capitalizeFirstAndLastLetters("aBCdefg") == "ABCdefG"
func capitalizeFirstAndLastLetters(text: String) -> String {
if text.isEmpty {
return ""
}
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased)
}
// 6. Write a function that takes a string and returns a string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters is a function that takes string and returns string with the first and last letters capitalized.
// capitalizeFirstAndLastLetters("") == ""
// capitalizeFirstAndLastLetters("a") == "A"
// capitalizeFirstAndLastLetters("hello") == "Hello"
// capitalizeFirstAndLastLetters("aBCdef") == "ABCdef"
// capitalizeFirstAndLastLetters("aBCdefg") == "ABCdefG"
result += char // cannot convert value of type 'Character' to expected argument type 'String'
return String(text.first!.uppercased) + text.substring(1) // no exact matches in call to instance method 'substring'
return String(text.first!.uppercased) + text.substring(1) // type '() -> String' cannot conform to 'LosslessStringConvertible'
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased) // type '() -> String' cannot conform to 'LosslessStringConvertible'
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased) // no exact matches in call to instance method 'substring'
return String(text.first!.uppercased) + text.substring(1, text.count - 1) + String(text.last!.uppercased) // type '() -> String' cannot conform to 'LosslessStringConvertible'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.all(where: { $0 < t })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return l.all(where: { $0 < t }) // value of type '[Int]' has no member 'all'
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i >= t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i >= t {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of vowels
// in the string.
//
// vowelCount("Hello") == 2
// vowelCount("Apple") == 2
// vowelCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of words in
// the string.
//
// wordCount("Hello") == 1
// wordCount("Hello, World!") == 2
// wordCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of consonants
// in the string.
//
// consonantCount("Hello") == 3
// consonantCount("Apple") == 5
// consonantCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of vowels
// in the string.
//
// vowelCount("Hello") == 2
// vowelCount("Apple") == 2
// vowelCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of words
// in the string.
//
// wordCount("Hello") == 1
// wordCount("Hello, World!") == 2
// wordCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the number of consonants
// in the string.
//
// consonantCount("Hello") == 3
// consonantCount("Apple") == 5
// consonantCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string and returns the number of vowels
// in the string.
//
// vowelCount("Hello") == 2
// vowelCount("Apple") == 2
// vowelCount("") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string and returns the number of words
// in the string.
//
// wordCount("Hello") == 1
// wordCount("Hello, World!")
func belowThreshold(l: [Int], t: Int) -> Bool {
for element in l {
if element >= t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
for element in l {
if element >= t {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 1.2.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2.15
// ---------------------------
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2.
// 인자를 받아서 반환하는 함수
// 함수의 인자는 언제나 하나여야 한다.
// 함수의 반환값은 언제나 하나여야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
// 함수의 인자와 반환값은 모두 옵션이 없어야 한다.
func add(x: Int, y: Int) -> Int {
return x + y
}
func square(x: Int) -> Int {
return x * x
}
func squareRoot(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
func sum(x: Int) -> Int {
var result = 0
for i in 1...x {
result += i
}
return result
}
func sumOfEvenNumbers(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 2 == 0 {
result += i
}
}
return result
}
func sumOfOddNumbers(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 2 != 0 {
result += i
}
}
return result
}
func sumOfMultiplesOf3And5(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 3 == 0 || i % 5 == 0 {
result += i
}
}
return result
}
func sumOfMultiplesOf3And5(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 3 == 0 && i % 5 == 0 {
result += i
}
}
return result
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2. Write a function that takes a number as an argument and returns the square of that number.
// square(2) == 4
// square(5) == 25
func square(x: Int) -> Int {
return x * x
}
// 3. Write a function that takes a number as an argument and returns the square root of that number.
// squareRoot(4) == 2
// squareRoot(9) == 3
func squareRoot(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
// 4. Write a function that takes a number as an argument and returns the factorial of that number.
// factorial(5) == 120
// factorial(0) == 1
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
// 5. Write a function that takes a number as an argument and returns the sum of all numbers from 1 to that number.
// sum(5) == 15
// sum(10) == 55
func sum(x: Int) -> Int {
var result = 0
for i in 1...x {
result += i
}
return result
}
// 6. Write a function that takes a number as an argument and returns the sum of all even numbers from 1 to that number.
// sumOfEvenNumbers(5) == 6
// sumOfEvenNumbers(10) == 30
func sumOfEvenNumbers(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 2 == 0 {
result += i
}
}
return result
}
// 7. Write a function that takes a number as an argument and returns the sum of all odd numbers from 1 to that number.
// sumOfOddNumbers(5) == 9
// sumOfOddNumbers(10) == 30
func sumOfOddNumbers(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 2 != 0 {
result += i
}
}
return result
}
// 8. Write a function that takes a number as an argument and returns the sum of all numbers from 1 to that number that are multiples of 3 or 5.
// sumOfMultiplesOf3And5(10) == 33
// sumOfMultiplesOf3And5(20) == 78
func sumOfMultiplesOf3And5(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 3 == 0 || i % 5 == 0 {
result += i
}
}
return result
}
// 9. Write a function that takes a number as an argument and returns the sum of all numbers from 1 to that number that are multiples of both 3 and 5.
// sumOfMultiplesOf3And5(10) == 33
// sumOfMultiplesOf3And5(20) == 78
func sumOfMultiplesOf3And5(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 3 == 0 && i % 5 == 0 {
result += i
}
}
return result
}
// 10. Write a function that takes a number as an argument and returns the sum of all numbers from 1 to that number that are multiples of both 3 and 7.
// sumOfMultiplesOf3And7(10) == 42
// sumOfMultiplesOf3And7(20) == 168
func sumOfMultiplesOf3And7(x: Int) -> Int {
var result = 0
for i in 1...x {
if i % 3 == 0 && i % 7 == 0 {
result += i
}
}
return result
func sumOfMultiplesOf3And5(x: Int) -> Int { // invalid redeclaration of 'sumOfMultiplesOf3And5(x:)'
func add(x: Int, y: Int) -> Int {
return x + y
}
func lengthOfString(string: String) -> Int {
return string.count
}
func lengthOfString(string: String) {
print(string.count)
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 3. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) -> Int {
return string.count
}
// 4. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 5. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 6. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 7. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 8. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 9. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 10. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 11. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 12. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 13. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 14. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 15. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 16. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 17. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 18. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 19. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 20. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 21. Write a function that takes a string and returns its length.
// lengthOfString("hello") == 5
func lengthOfString(string: String) {
print(string.count)
}
// 22. Write a function that takes a string and returns
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2.
// 1.
// 2.
// 3.
// 4.
// 5.
// 6.
// 7.
// 8.
// 9.
// 10.
// 11.
// 12.
// 13.
// 14.
// 15.
// 16.
// 17.
// 18.
// 19.
// 20.
// 21.
// 22.
// 23.
// 24.
// 25.
// 26.
// 27.
// 28.
// 29.
// 30.
// 31.
// 32.
// 33.
// 34.
// 35.
// 36.
// 37.
// 38.
// 39.
// 40.
// 41.
// 42.
// 43.
// 44.
// 45.
// 46.
// 47.
// 48.
// 49.
// 50.
// 51.
// 52.
// 53.
// 54.
// 55.
// 56.
// 57.
// 58.
// 59.
// 60.
// 61.
// 62.
// 63.
// 64.
// 65.
// 66.
// 67.
// 68.
// 69.
// 70.
// 71.
// 72.
// 73.
// 74.
// 75.
// 76.
// 77.
// 78.
// 79.
// 80.
// 81.
// 82.
// 83.
// 84.
// 85.
// 86.
// 87.
// 88.
// 89.
// 90.
// 91.
// 92.
// 93.
// 94.
// 95.
// 96.
// 97.
// 98.
// 99.
// 100.
// 101.
// 102.
// 103.
// 104.
// 105.
// 106.
// 107.
// 108.
// 109.
// 110.
// 111.
// 112.
// 113.
// 114.
// 115.
// 116.
// 117.
// 118.
// 119.
// 120.
// 121.
// 122.
// 123.
// 124.
// 125.
// 126.
// 127.
// 128.
// 129.
// 130.
// 131.
// 132.
// 133.
// 134.
// 135.
// 136.
// 137.
// 138.
// 139.
// 140.
// 141.
// 142.
// 143.
// 144.
// 145.
// 146.
// 147.
// 148.
// 149.
// 150.
// 151.
// 152.
// 153.
// 154.
// 155.
// 156.
// 157.
// 158.
// 159.
// 16
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the length of the string.
// length("hello") == 5
// length("") == 0
// length("a") == 1
// length("aa") == 2
// length("aaa") == 3
// length("aaaa") == 4
// length("aaaaa") == 5
// length("aaaaaa") == 6
// length("aaaaaaa") == 7
// length("aaaaaaaa") == 8
// length("aaaaaaaaa") == 9
// length("aaaaaaaaaa") == 10
// length("aaaaaaaaaaa") == 11
// length("aaaaaaaaaaaa") == 12
// length("aaaaaaaaaaaaa") == 13
// length("aaaaaaaaaaaaaa") == 14
// length("aaaaaaaaaaaaaaa") == 15
// length("aaaaaaaaaaaaaaaa") == 16
// length("aaaaaaaaaaaaaaaaa") == 17
// length("aaaaaaaaaaaaaaaaaa") == 18
// length("aaaaaaaaaaaaaaaaaaa") == 19
// length("aaaaaaaaaaaaaaaaaaaa") == 20
// length("aaaaaaaaaaaaaaaaaaaaa") == 21
// length("aaaaaaaaaaaaaaaaaaaaaa") == 22
// length("aaaaaaaaaaaaaaaaaaaaaaa") == 23
// length("aaaaaaaaaaaaaaaaaaaaaaaa") == 24
// length("aaaaaaaaaaaaaaaaaaaaaaaaa") == 25
// length("aaaaaaaaaaaaaaaaaaaaaaaaaa") == 26
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaa") == 27
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 28
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 29
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 30
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 31
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 32
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 33
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 34
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 35
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 36
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 37
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 38
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 39
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 40
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 41
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 42
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 43
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 44
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 45
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 46
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 47
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 48
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 49
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 50
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 51
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 52
// length("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2. 使用函数名作为参数
// 使用函数名作为参数,可以避免使用多余的括号
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 3. 使用函数名作为返回值
// 使用函数名作为返回值,可以避免使用多余的括号
// let result = add(x: 2, y: 3)
// result == 5
// let result = add(x: 5, y: 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 4. 使用函数名作为参数和返回值
// 使用函数名作为参数和返回值,可以避免使用多余的括号
// let result = add(x: 2, y: 3)
// result == 5
// let result = add(x: 5, y: 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 5. 使用函数名作为参数和返回值,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,可以避免使用多余的括号
// let result = add(2, 3)
// result == 5
// let result = add(5, 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 6. 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,可以避免使用多余的括号
// let result = add(2, 3)
// result == 5
// let result = add(5, 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 7. 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,可以避免使用多余的括号
// let result = add(2, 3)
// result == 5
// let result = add(5, 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 8. 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,可以避免使用多余的括号
// let result = add(2, 3)
// result == 5
// let result = add(5, 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 9. 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,可以避免使用多余的括号
// let result = add(2, 3)
// result == 5
// let result = add(5, 7)
// result == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 10. 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断,并使用类型推断
// 使用函数名作为参数和返回值,并使用类型推断,并使用类型推断,
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2.
// 아래 함수는 인자로 받은 문자열을 반대로 뒤집어 반환하는 함수입니다.
// 예를 들어 "hello"를 입력하면 "olleh"를 반환합니다.
// 아래 함수를 완성해 보세요.
// 문자열을 반대로 뒤집는 함수 reverseString(s: String) -> String
// 1.
// 아래 함수는 인자로 받은 문자열을 반대로 뒤집어 반환하는 함수입니다.
// 예를 들어 "hello"를 입력하면 "olleh"를 반환합니다.
// 아래 함수를 완성해 보세요.
// 문자열을 반대로 뒤집는 함수 reverseString(s: String) -> String
// 2.
// 아래 함수는 인자로 받은 문자열을 반대로 뒤집어 반환하는 함수입니다.
// 예를 들어 "hello"를 입력하면 "olleh"를 반환합니다.
// 아래 함수를 완성해 보세요.
// 문자열을 반대로 뒤집는 함수 reverseString(s: String) -> String
// 3.
// 아래 함수는 인자로 받은 문자열을 반대로 뒤집어 반환하는 함수입니다.
// 예를 들어 "hello"를 입력하면 "olleh"를 반환합니다.
// 아래 함수를 완성해 보세요.
// 문자열을 반대로 뒤집는 함수 reverseString(s: String) -> String
// 4.
// 아래 함수는 인자로 받은 문자열을 반대로 뒤집어 반환하는 함수입니다.
// 예를 들어 "hello"를 입력하면 "olleh"를 반환합니다.
// 아래 함수를 완성해 보세요.
// 문자열을 반대로 뒤집는 함수 reverseString(s: String) -> String
// 5.
// 아래
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.154.155.156.157.158.159.160.161.162.163.164.165.166.167.168.169.170.171.172.173.174.175.176.177.178.179.180.181.182.183.184.185.186.187.188.189.190.191.192.193.194.195.196.197.198.199.200.201.202.203.204.205.206.207.208.209.210.211.212.213.214.215.216.217.218.219.220.221.222.223.224.225.226.227.228.229.230.231.232.233.234.235.236.237.238.239.240.241.242.243.244.245.246.247.248.249.250.251.252.253.254.255.256.257.258.259.260.261.262.263.264.265.266.267.268.269.270.271.272.273.274.275.276.277.278.279.280.
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 2.1.2.2.1
// 함수 표현식
// 함수 표현식은 함수를 생성하는 것과 동일하다.
// 함수 표현식을 사용하면 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
// 함수 표현식은 함수를 생성하는 대신 함수를 바로 실행할 수 있다.
//
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// 1.1.2.2
// 1.1.2.3
// 1.1.2.4
// 1.1.2.5
// 1.1.2.6
// 1.1.2.7
// 1.1.2.8
// 1.1.2.9
// 1.1.2.10
// 1.1.2.11
// 1.1.2.12
// 1.1.2.13
// 1.1.2.14
// 1.1.2.15
// 1.1.2.16
// 1.1.2.17
// 1.1.2.18
// 1.1.2.19
// 1.1.2.20
// 1.1.2.21
// 1.1.2.22
// 1.1.2.23
// 1.1.2.24
// 1.1.2.25
// 1.1.2.26
// 1.1.2.27
// 1.1.2.28
// 1.1.2.29
// 1.1.2.30
// 1.1.2.31
// 1.1.2.32
// 1.1.2.33
// 1.1.2.34
// 1.1.2.35
// 1.1.2.36
// 1.1.2.37
// 1.1.2.38
// 1.1.2.39
// 1.1.2.40
// 1.1.2.41
// 1.1.2.42
// 1.1.2.43
// 1.1.2.44
// 1.1.2.45
// 1.1.2.46
// 1.1.2.47
// 1.1.2.48
// 1.1.2.49
// 1.1.2.50
// 1.1.2.51
// 1.1.2.52
// 1.1.2.53
// 1.1.2.54
// 1.1.2.55
// 1.1.2.56
// 1.1.2.57
// 1.1.2.58
// 1.1.2.59
// 1.1.2.60
// 1.1.2.61
// 1.1.2.62
// 1.1.2.63
// 1.1.2.64
// 1.1.2.65
// 1.1.2.66
// 1.1.2.67
// 1.1.2.68
// 1.1.2.69
// 1.1.2.70
// 1.1.2.71
// 1.1.2.72
// 1.1.2.73
// 1.1.2.74
// 1.1.2.75
// 1.1.2.76
// 1.1.2.77
// 1.1.2.78
// 1.1.2.79
// 1.1.2.80
// 1.1.2.81
// 1.1.2.82
// 1.1.2.83
// 1.1.2.84
// 1.1.2.85
// 1.1.2.86
// 1.1.2.87
// 1.1.2.88
// 1.1.2.89
// 1.1.2.90
// 1.1.2.91
// 1.1.2.92
// 1.1.2.93
// 1.1.2.94
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
for i in 0..<s0.count {
if s0[i] != s1[i] {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
if s0[i] != s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s0[i] != s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func sameChars(s0: String, s1: String) -> Bool {
var i = 0
while i < s0.count {
if s0[i] != s1[i] {
return false
}
i += 1
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var i = 0
while i < s0.count {
if s0[i] != s1[i] {
return false
}
i += 1
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
if s0[i] != s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s0[i] != s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
return s0.count == s1.count && s0.count == 0 ? true : s0.count == 0 ? false : s0.count == 1 ? true : s0.count == 1 ? false : s0.count == 2 ? true : s0.count == 2 ? false : s0.count == 3 ? true : s0.count == 3 ? false : s0.count == 4 ? true : s0.count == 4 ? false : s0.count == 5 ? true : s0.count == 5 ? false : s0.count == 6 ? true : s0.count == 6 ? false : s0.count == 7 ? true : s0.count == 7 ? false : s0.count == 8 ? true : s0.count == 8 ? false : s0.count == 9 ? true : s0.count == 9 ? false : s0.count == 10 ? true : s0.count == 10 ? false : s0.count == 11 ? true : s0.count == 11 ? false : s0.count == 12 ? true : s0.count == 12 ? false : s0.count == 13 ? true : s0.count == 13 ? false : s0.count == 14 ? true : s0.count == 14 ? false : s0.count == 15 ? true : s0.count == 15 ? false : s0.count == 16 ? true : s0.count == 16 ? false : s0.count == 17 ? true : s0.count == 17 ? false : s0.count == 18 ? true : s0.count == 18 ? false : s0.count == 19 ? true : s0.count == 19 ? false : s0.count == 20 ? true : s0.count == 20 ? false : s0.count == 21 ? true : s0.count == 21 ? false : s0.count == 22 ? true : s0.count == 22 ? false : s0.count == 23 ? true : s0.count == 23 ? false : s0.count == 24 ? true : s0.count == 24 ? false : s0.count == 25 ? true : s0.count == 25 ? false : s0.count == 26 ? true : s0.count == 26 ? false : s0.count == 27 ? true : s0.count == 27 ? false : s0.count == 28 ? true : s0.count == 28 ? false : s0.count == 29 ? true : s0.count == 29 ? false : s0.count == 30 ? true : s0.count == 30 ? false : s0.count == 31 ? true : s0.count == 31 ? false : s0.count == 32 ? true : s0.count == 32 ? false : s0.count == 33 ? true : s0.count == 33 ? false : s0.count == 34 ? true : s0.count == 34 ? false : s0.count == 35 ? true : s0.count == 35 ? false : s0.count == 36 ? true : s0.count == 36 ? false : s0.count == 37 ? true : s0.count == 37 ? false : s0.count == 38 ? true : s0.count == 38 ? false : s0.count == 39 ? true : s0.count == 39 ? false : s0.count == 40 ? true : s0.count == 40 ? false : s0.count == 41 ? true : s0.count == 41 ? false : s0.count == 42 ? true : s0.count == 42 ? false
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabc") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "dddddddabc", s1: "abcd") == true) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcd", s1: "dddddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "abcd", s1: "dddddddabcf") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false) // cannot find 'sameChars' in scope
XCTAssertTrue(sameChars(s0: "aabb", s1: "aaccc") == false) // cannot find 'sameChars' in scope
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
struct Test {
var input: String
var expected: Bool
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Test {
var input: String
var expected: Bool
}
var tests: [Test] = [
Test(input: "eabcdzzzz", expected: true),
Test(input: "dddzzzzzzzddeddabc", expected: true),
Test(input: "dddddddabc", expected: true),
Test(input: "eabcd", expected: false),
Test(input: "abcd", expected: false),
Test(input: "dddddddabc", expected: false),
Test(input: "dddddddabc", expected: false),
Test(input: "abcd", expected: false),
Test(input: "eabcdzzzz", expected: false),
]
var testIndex = 0
while (testIndex < tests.count) {
var test = tests[testIndex]
var result = sameChars(s0: test.input, s1: test.input)
if (result != test.expected) {
print("\n\nERROR: test #" + testIndex.toString())
print(" input: " + test.input)
print(" expected: " + test.expected)
print(" result: " + result)
}
testIndex += 1
}<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a string with the first
// character of each word capitalized.
//
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
// capitalizeFirst("hello world") == "Hello World"
//
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0Set = Set<Character>()
var s1Set = Set<Character>()
for c in s0 {
s0Set.insert(c)
}
for c in s1 {
s1Set.insert(c)
}
return s0Set == s1Set
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var s0 = s0
var s1 = s1
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
var s0 = s0 // variable 's0' was never mutated; consider changing to 'let' constant
var s1 = s1 // variable 's1' was never mutated; consider changing to 'let' constant
if s0[i] == s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s0[i] == s1[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
// -----------------------------------------------------------------------------
// 2.1.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2.1.15
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 0 {
return 0
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 0 {
return 0
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.15
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.16
// ---------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
print(fib(10))
print(fib(1))
print(fib(8))
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// 1.2.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fib(n - 1) + fib(n - 2)
}
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// -----------------------------------------------------------------------------
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
var count = 0
for char in s {
if char == " " {
count += 1
}
}
return count + 1
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
func countAlphabetic(s: String) -> Int {
var count = 0
for char in s {
if char.isAlphabetic {
count += 1
}
}
return count
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// 11. Write a function that takes a string as input and returns the number of vowels in the string.
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels("Aa") == 2
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 12. Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
// countWords("") == 0
// countWords("Hello world!!!") == 3
func countWords(s: String) -> Int {
var count = 0
for char in s {
if char == " " {
count += 1
}
}
return count + 1
}
// 13. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// countUppercase("Hello world") == 2
// countUppercase("Hello World") == 2
// countUppercase("") == 0
// countUppercase("Hello World!") == 2
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
// 14. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// countLowercase("Hello world") == 5
// countLowercase("Hello World") == 5
// countLowercase("") == 0
// countLowercase("Hello World!") == 5
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
// 15. Write a function that takes a string as input and returns the number of digits in the string.
// countDigits("Hello world") == 0
// countDigits("Hello World") == 0
// countDigits("") == 0
// countDigits("Hello World!") == 1
// countDigits("12345") == 5
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
// 16. Write a function that takes a string as input and returns the number of alphabetic characters in the string.
// countAlphabetic("Hello world") == 5
// countAlphabetic("Hello World") == 5
// countAlphabetic("") == 0
// countAlphabetic("Hello World!") == 5
// countAlphabetic("12345") == 0
// countAlphabetic("abcdefg") == 7
func countAlphabetic(s: String) -> Int {
var count = 0
for char in s {
if char.isAlphabetic {
count += 1
}
}
return count
}
// 17. Write a function that takes a string as input and returns the number of consonants in the string.
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
if char.isAlphabetic { // value of type 'Character' has no member 'isAlphabetic'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of times
// the letter "a" appears in it.
// countAs("apple") == 1
// countAs("apple apple") == 2
// countAs("apple apple apple") == 3
// countAs("apple apple apple a") == 4
// countAs("apple apple apple a apple") == 5
// countAs("apple apple apple a apple apple") == 6
// countAs("apple apple apple a apple apple apple") == 7
// countAs("apple apple apple a apple apple apple a") == 8
// countAs("apple apple apple a apple apple apple a apple") == 9
// countAs("apple apple apple a apple apple apple a apple apple") == 10
// countAs("apple apple apple a apple apple apple a apple apple a") == 11
// countAs("apple apple apple a apple apple apple a apple apple a apple") == 12
// countAs("apple apple apple a apple apple apple a apple apple a apple apple") == 13
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a") == 14
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple") == 15
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple") == 16
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple") == 17
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple") == 18
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple") == 19
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple") == 20
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple") == 21
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple") == 22
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple") == 23
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple") == 24
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple") == 25
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple apple") == 26
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple apple apple") == 27
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple apple apple apple") == 28
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple") == 29
// countAs("apple apple apple a apple apple apple a apple apple a apple apple a apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple apple
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 1.1.1
// Given a string, return the number of times that a substring appears as a
// contiguous substring.
// countSubstring("apple", "ple") == 1
// countSubstring("apple", "plep") == 0
// countSubstring("apple", "plepp") == 0
// countSubstring("apple", "pleppple") == 1
// countSubstring("apple", "plepppleple") == 2
// countSubstring("apple", "pleppplepleple") == 2
// countSubstring("apple", "plepppleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "plepppleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleplepleple") == 2
// countSubstring("apple", "pleppplepleple
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.14
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.15
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
switch bracket {
case "<":
stack.append(bracket)
case ">":
if stack.isEmpty {
return false
}
stack.pop()
default:
return false
}
}
return stack.isEmpty
}
func firstRecurringCharacter(input: String) -> String? {
var seen = [Character]()
for character in input {
if seen.contains(character) {
return String(character)
}
seen.append(character)
}
return nil
}
func mostCommonCharacter(input: String) -> String {
var counts = [Int]()
for character in input {
counts[Int(character)] = counts[Int(character)] + 1
}
var max = 0
var maxCharacter = ""
for i in 0..<counts.count {
if counts[i] > max {
max = counts[i]
maxCharacter = String(character: i)
}
}
return maxCharacter
}
func firstNonRepeatingCharacter(input: String) -> Int {
var seen = [Character]()
var counts = [Int]()
for character in input {
if seen.contains(character) {
counts[Int(character)] = counts[Int(character)] + 1
} else {
seen.append(character)
counts.append(1)
}
}
var min = Int.max
var index = -1
for i in 0..<counts.count {
if counts[i] == 1 && i < min {
min = counts[i]
index = i
}
}
return index
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
switch bracket {
case "<":
stack.append(bracket)
case ">":
if stack.isEmpty {
return false
}
stack.pop()
default:
return false
}
}
return stack.isEmpty
}
// 2.
// Given a string, return the first recurring character in it, or null if there are no recurring characters.
// firstRecurringCharacter("abcd") == null
// firstRecurringCharacter("abcdabcd") == "d"
// firstRecurringCharacter("abcdabcde") == "d"
// firstRecurringCharacter("abcde") == null
func firstRecurringCharacter(input: String) -> String? {
var seen = [Character]()
for character in input {
if seen.contains(character) {
return String(character)
}
seen.append(character)
}
return nil
}
// 3.
// Given a string, return the character that is most commonly used in the string.
// mostCommonCharacter("abcccccccd") == "c"
// mostCommonCharacter("apple") == "p"
func mostCommonCharacter(input: String) -> String {
var counts = [Int]()
for character in input {
counts[Int(character)] = counts[Int(character)] + 1
}
var max = 0
var maxCharacter = ""
for i in 0..<counts.count {
if counts[i] > max {
max = counts[i]
maxCharacter = String(character: i)
}
}
return maxCharacter
}
// 4.
// Given a string, find the index of the first non-repeating character.
// firstNonRepeatingCharacter("abcd") == 0
// firstNonRepeatingCharacter("abcdcd") == 2
// firstNonRepeatingCharacter("abcdcdx") == 4
// firstNonRepeatingCharacter("abcdcdxzz") == 6
func firstNonRepeatingCharacter(input: String) -> Int {
var seen = [Character]()
var counts = [Int]()
for character in input {
if seen.contains(character) {
counts[Int(character)] = counts[Int(character)] + 1
} else {
seen.append(character)
counts.append(1)
}
}
var min = Int.max
var index = -1
for i in 0..<counts.count {
if counts[i] == 1 && i < min {
min = counts[i]
index = i
}
}
return index
}
// 5.
// Given a string, find the index of the first non-repeating character.
// firstNonRepeatingCharacter("abcd") == 0
// firstNonRepeatingCharacter("abcdcd") == 2
// firstNonRepeatingCharacter("abcdcdx") == 4
// firstNonRepeatingCharacter("abcdcdxzz") == 6
func firstNonRepeatingCharacter(input: String) -> Int {
var seen = [Character]()
var counts = [Int]()
for character in input {
if seen.contains(character) {
counts[Int(character)] = counts[Int(character)] + 1
} else {
seen.append(character)
counts.append(1)
}
}
var min = Int.max
var index = -1
for i in 0..<counts.count {
if counts[i] == 1 && i < min {
min = counts[i]
index = i
}
}
return index
}
// 6.
// Given a string, find the index of the first non-repeating character.
// firstNonRepeatingCharacter("abcd") == 0
// firstNonRepeatingCharacter("abcdcd") == 2
// firstNonRepeatingCharacter("abcdcdx") == 4
// firstNonRepeatingCharacter("abcdcd
stack.pop() // value of type '[Character]' has no member 'pop'
counts[Int(character)] = counts[Int(character)] + 1 // no exact matches in call to initializer
counts[Int(character)] = counts[Int(character)] + 1 // no exact matches in call to initializer
maxCharacter = String(character: i) // no exact matches in call to initializer
counts[Int(character)] = counts[Int(character)] + 1 // no exact matches in call to initializer
counts[Int(character)] = counts[Int(character)] + 1 // no exact matches in call to initializer
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func reverseString(s: String) -> String {
var reversed = ""
for char in s {
reversed = char + reversed
}
return reversed
}
func removeSpaces(s: String) -> String {
var result = ""
for char in s {
if char != " " {
result += char
}
}
return result
}
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func removeVowelsAndY(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b") == "b a"
// reverseString("a b c") == "c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
func reverseString(s: String) -> String {
var reversed = ""
for char in s {
reversed = char + reversed
}
return reversed
}
// 11. Write a function that takes a string as input and returns the string with all the spaces removed.
// removeSpaces("hello world") == "helloworld"
// removeSpaces("") == ""
// removeSpaces("a") == "a"
// removeSpaces("a b") == "ab"
// removeSpaces("a b c") == "abc"
// removeSpaces("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "abcdefghijklmnopqrstuvwxyz"
func removeSpaces(s: String) -> String {
var result = ""
for char in s {
if char != " " {
result += char
}
}
return result
}
// 12. Write a function that takes a string as input and returns the string with all the vowels removed.
// removeVowels("hello world") == "hll wrld"
// removeVowels("") == ""
// removeVowels("a") == ""
// removeVowels("a b") == "b"
// removeVowels("a b c") == "c"
// removeVowels("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "c d f g h j k l m n r s t v w x z"
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 13. Write a function that takes a string as input and returns the string with all the vowels removed, but with the letter "y" replaced by "i".
// removeVowelsAndY("hello world") == "hll wrld"
// removeVowelsAndY("") == ""
// removeVowelsAndY("a") == ""
// removeVowelsAndY("a b") == "b"
// removeVowelsAndY("a b c") == "c"
// removeVowelsAndY("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "c d f g h j k l m n r s t v w x z"
func removeVowelsAndY(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "y" {
result += char
}
}
return result
}
stack.pop() // value of type '[Character]' has no member 'pop'
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
var count = 0
var word = ""
for char in s {
if char == " " {
count += 1
word = ""
} else {
word += char
}
}
return count + 1
}
func countConsonants(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
} else if char == " " {
continue
} else {
count += 1
}
}
return count
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == "A" || char == "B" || char == "C" || char == "D" || char == "E" || char == "F" || char == "G" || char == "H" || char == "I" || char == "J" || char == "K" || char == "L" || char == "M" || char == "N" || char == "O" || char == "P" || char == "Q" || char == "R" || char == "S" || char == "T" || char == "U" || char == "V" || char == "W" || char == "X" || char == "Y" || char == "Z" {
count += 1
}
}
return count
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// 12. Write a function that takes a string as input and returns the number of vowels in the string.
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels("bcdfghjklmnpqrstvwxyz") == 0
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 13. Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world") == 2
// countWords("") == 0
// countWords("a b c") == 3
// countWords("a b c d e f g h i j k l m n o p q r s t u v w x y z") == 26
func countWords(s: String) -> Int {
var count = 0
var word = ""
for char in s {
if char == " " {
count += 1
word = ""
} else {
word += char
}
}
return count + 1
}
// 14. Write a function that takes a string as input and returns the number of consonants in the string.
// countConsonants("Hello world") == 5
// countConsonants("") == 0
// countConsonants("a b c") == 0
// countConsonants("a b c d e f g h i j k l m n o p q r s t u v w x y z") == 26
func countConsonants(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
} else if char == " " {
continue
} else {
count += 1
}
}
return count
}
// 15. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// countUppercase("Hello world") == 2
// countUppercase("") == 0
// countUppercase("a b c") == 0
// countUppercase("A B C") == 3
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == "A" || char == "B" || char == "C" || char == "D" || char == "E" || char == "F" || char == "G" || char == "H" || char == "I" || char == "J" || char == "K" || char == "L" || char == "M" || char == "N" || char == "O" || char == "P" || char == "Q" || char == "R" || char == "S" || char == "T" || char == "U" || char == "V" || char == "W" || char == "X" || char == "Y" || char == "Z" {
count += 1
}
}
return count
}
// 16. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// countLowercase("Hello world") == 5
// countLowercase("") == 0
// countLowercase("a b c") == 0
// countLowercase("a B c")
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
word += char // cannot convert value of type 'Character' to expected argument type 'String'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var num = 0
while i < input.count && Character(input[i]).isDigit {
num = num * 10 + Character(input[i]).asInt!
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
func firstTwo(input: String) -> String {
if input.count < 2 {
return input
}
return input[0..<2]
}
func withouEnd2(input: String) -> String {
return input[1..<input.count-1]
}
func equalIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for i in 0..<input.count {
if input[i] == "i" && input[i+1] == "s" {
isCount += 1
} else if input[i] == "n" && input[i+1] == "o" {
notCount += 1
}
}
return isCount == notCount
}
func atFirst(input: String) -> String {
if input.count < 2 {
return input + "@"
}
return input[0..<2]
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// 2. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var num = 0
while i < input.count && Character(input[i]).isDigit {
num = num * 10 + Character(input[i]).asInt!
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
// 3. Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(input: String) -> String {
if input.count < 2 {
return input
}
return input[0..<2]
}
// 4. Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2.
// withouEnd2("Hello") == "ell"
// withouEnd2("java") == "av"
// withouEnd2("coding") == "odin"
func withouEnd2(input: String) -> String {
return input[1..<input.count-1]
}
// 5. Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).
// equalIsNot("This is not") == true
// equalIsNot("This is notnot") == false
// equalIsNot("noisxxnotyynotxisi") == true
func equalIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for i in 0..<input.count {
if input[i] == "i" && input[i+1] == "s" {
isCount += 1
} else if input[i] == "n" && input[i+1] == "o" {
notCount += 1
}
}
return isCount == notCount
}
// 6. Given a string, return a string length 2 made of its first 2 chars. If the string length is less than 2, use '@' for the missing chars.
// atFirst("hello") == "he"
// atFirst("hi") == "hi"
// atFirst("h") == "h@"
func atFirst(input: String) -> String {
if input.count < 2 {
return input + "@"
}
return input[0..<2]
}
// 7. Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be
stack.pop() // value of type '[Character]' has no member 'pop'
if Character(input[i]).isDigit { // missing argument label 'extendedGraphemeClusterLiteral:' in call
if Character(input[i]).isDigit { // value of type 'Character' has no member 'isDigit'
while i < input.count && Character(input[i]).isDigit { // missing argument label 'extendedGraphemeClusterLiteral:' in call
while i < input.count && Character(input[i]).isDigit { // value of type 'Character' has no member 'isDigit'
num = num * 10 + Character(input[i]).asInt! // missing argument label 'extendedGraphemeClusterLiteral:' in call
num = num * 10 + Character(input[i]).asInt! // value of type 'Character' has no member 'asInt'
return input[0..<2] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return input[1..<input.count-1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if input[i] == "i" && input[i+1] == "s" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if input[i] == "i" && input[i+1] == "s" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if input[i] == "n" && input[i+1] == "o" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if input[i] == "n" && input[i+1] == "o" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return input[0..<2] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string == string.reversed()
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns true if the string is a
// palindrome.
// palindrome("racecar") == true
// palindrome("hello") == false
// palindrome("") == true
func palindrome(string: String) -> Bool {
return string ==
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
return string == string.reversed() // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
func goodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i < j && nums[i] == nums[j] {
count += 1
}
}
}
return count
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
// -----------------------------------------------------------------------------
// 13. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// nums = [1, 2, 3, 1, 1, 3]
// goodPairs(nums) == 4
// Explanation: There are 4 good pairs (0, 1), (0, 2), (2, 3), (4, 5) 0-indexed.
func goodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i < j && nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 14. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// nums = [1, 2, 3, 1, 1, 3]
// goodPairs(nums) == 4
// Explanation: There are 4 good pairs (0, 1), (0, 2), (2, 3), (4, 5) 0-indexed.
func goodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i < j && nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 15. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// nums = [1, 2, 3, 1, 1, 3]
// goodPairs(nums) == 4
// Explanation: There are 4 good pairs (0, 1), (0, 2), (2, 3), (4, 5) 0-indexed.
func goodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i < j && nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 16. Given an array of integers nums, return the number of good pairs.
reversed += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i - 1] {
increasing = false
}
if l[i] > l[i - 1] {
decreasing = false
}
}
return increasing || decreasing
}
public func test_monotonic() {
print("\n--------------------------------------------------------------------------------")
print("monotonic")
print("--------------------------------------------------------------------------------")
print("monotonic([1, 2, 4, 20]) == true")
print(monotonic([1, 2, 4, 20]))
print("monotonic([1, 20, 4, 10]) == false")
print(monotonic([1, 20, 4, 10]))
print("monotonic([4, 1, 0, -10]) == true")
print(monotonic([4, 1, 0, -10]))
}
public func run() {
test_monotonic()
}
import Foundation
public class Solution {
public func reverseWords(s: String) -> String {
var words = s.split(separator: " ")
var result = ""
for word in words {
result += String(word.reversed()) + " "
}
return result.trim()
}
}
public func test_reverseWords() {
print("--------------------------------------------------------------------------------")
print("reverseWords")
print("--------------------------------------------------------------------------------")
print("reverseWords(\"the sky is blue\") == \"blue is sky the\"")
print(Solution().reverseWords("the sky is blue"))
print("reverseWords(\" hello world! \") == \"world! hello\"")
print(Solution().reverseWords(" hello world! "))
print("reverseWords(\"a good example\") == \"example good a\"")
print(Solution().reverseWords("a good example"))
}
public func run() {
test_reverseWords()
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i - 1] {
increasing = false
}
if l[i] > l[i - 1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
public func test_monotonic() {
print("\n--------------------------------------------------------------------------------")
print("monotonic")
print("--------------------------------------------------------------------------------")
print("monotonic([1, 2, 4, 20]) == true")
print(monotonic([1, 2, 4, 20]))
print("monotonic([1, 20, 4, 10]) == false")
print(monotonic([1, 20, 4, 10]))
print("monotonic([4, 1, 0, -10]) == true")
print(monotonic([4, 1, 0, -10]))
}
// -----------------------------------------------------------------------------
public func run() {
test_monotonic()
}
// -----------------------------------------------------------------------------<|endoftext|>//
// main.swift
// SwiftPlayground
//
// Created by 임성민 on 2021/02/21.
//
import Foundation
public class Solution {
public func reverseWords(s: String) -> String {
var words = s.split(separator: " ")
var result = ""
for word in words {
result += String(word.reversed()) + " "
}
return result.trim()
}
}
public func test_reverseWords() {
print("--------------------------------------------------------------------------------")
print("reverseWords")
print("--------------------------------------------------------------------------------")
print("reverseWords(\"the sky is blue\") == \"blue is sky the\"")
print(Solution().reverseWords("the sky is blue"))
print("reverseWords(\" hello world! \") == \"world! hello\"")
print(Solution().reverseWords(" hello world! "))
print("reverseWords(\"a good example\") == \"example good a\"")
print(Solution().reverseWords("a good example"))
}
public func run() {
test_reverseWords()
}
// -----------------------------------------------------------------------------<|endoftext|>//
// main.swift
// SwiftPlayground
//
// Created by 임성민 on 2021/02/21.
//
import Foundation
public class Solution {
public func reverseWords(s: String) -> String {
var words = s.split(separator: " ")
var result = ""
for word in words {
result += String(word.reversed()) + " "
}
return result.trim()
}
}
public func test_reverseWords() {
print("--------------------------------------------------------------------------------")
print("reverseWords")
print("------------------------------------------------------------
print(monotonic([1, 2, 4, 20])) // missing argument label 'l:' in call
print(monotonic([1, 20, 4, 10])) // missing argument label 'l:' in call
print(monotonic([4, 1, 0, -10])) // missing argument label 'l:' in call
return result.trim() // value of type 'String' has no member 'trim'
print(Solution().reverseWords("the sky is blue")) // missing argument label 's:' in call
print(Solution().reverseWords(" hello world! ")) // missing argument label 's:' in call
print(Solution().reverseWords("a good example")) // missing argument label 's:' in call
public func run() { // invalid redeclaration of 'run()'
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
func findPair(l: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
if l[i] + l[j] == target {
result = [l[i], l[j]]
}
}
}
return result
}
func evenNumbers(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func oddNumbers(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i % 2 != 0 {
result.append(i)
}
}
return result
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a non-empty array of distinct integers and an integer representing a target.
// If any two numbers in the input array sum to the target, return them in an array.
// Example: findPair([1, 2, 3, 4], 5) == [1, 4]
func findPair(l: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
for j in i+1..<l.count {
if l[i] + l[j] == target {
result = [l[i], l[j]]
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of integers and returns a new array containing all the even numbers from the original array.
// Example: evenNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 4, 6, 8, 10]
func evenNumbers(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of integers and returns a new array containing all the odd numbers from the original array.
// Example: oddNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 3, 5, 7, 9]
func oddNumbers(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i % 2 != 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes an array of integers and returns a new array containing all the even numbers from the original array, and all the odd numbers from the original array.
// Example: evenOdd([1, 2, 3,
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b") == "b a"
// reverseString("a b c") == "c b a"
// reverseString("a b c d") == "d c b a"
// reverseString("a b c d e") == "e d c b a"
// reverseString("a b c d e f") == "f e d c b a"
// reverseString("a b c d e f g") == "g f e d c b a"
// reverseString("a b c d e f g h") == "h g f e d c b a"
// reverseString("a b c d e f g h i") == "i h g f e d c b a"
// reverseString("a b c d e f g h i j") == "j i h g f e d c b a"
// reverseString("a b c d e f g h i j k") == "k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l") == "l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m") == "m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n") == "n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o") == "o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p") == "p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q") == "q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r") == "r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s") == "s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t") == "t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u") == "u t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v") == "v w u t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v w") == "w x v t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 1.1.1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.8
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.9
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.10
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.11
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.12
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.13
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1.1.14
// ---------------------------------------------------------------------
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
print(monotonic([1, 2, 4, 20]))
print(monotonic([1, 20, 4, 10]))
print(monotonic([4, 1, 0, -10]))
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
func pivotIndex(nums: [Int]) -> Int {
var leftSum = 0
var rightSum = 0
for i in nums {
rightSum += i
}
for i in 0..<nums.count {
if leftSum == rightSum {
return i
}
leftSum += nums[i]
rightSum -= nums[i]
}
return -1
}
func pivotIndex(nums: [Int]) -> Int {
var leftSum = 0
var rightSum = 0
for i in 0..<nums.count {
rightSum += nums[i]
}
for i in 0..<nums.count {
if leftSum == rightSum {
return i
}
leftSum += nums[i]
rightSum -= nums[i]
}
return -1
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
// -----------------------------------------------------------------------------
// 15. Given an array of integers nums, write a method that returns the "pivot" index of this array.
// We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
// If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
// pivotIndex([1, 7, 3, 6, 5, 6]) == 3
// pivotIndex([1, 2, 3]) == -1
// pivotIndex([2, 1, -1]) == 0
func pivotIndex(nums: [Int]) -> Int {
var leftSum = 0
var rightSum = 0
for i in nums {
rightSum += i
}
for i in 0..<nums.count {
if leftSum == rightSum {
return i
}
leftSum += nums[i]
rightSum -= nums[i]
}
return -1
}
// -----------------------------------------------------------------------------
// 16. Given an array of integers nums, write a method that returns the "pivot" index of this array.
// We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
// If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
// pivotIndex([1, 7, 3, 6, 5, 6]) == 3
// pivotIndex([1, 2, 3]) == -1
// pivotIndex([2, 1, -1]) == 0
func pivotIndex(nums: [Int]) -> Int {
var leftSum = 0
var rightSum = 0
for i in 0..<nums.count {
rightSum += nums[i]
}
for i in 0..<nums.count {
if leftSum == rightSum {
return i
}
leftSum += nums[i]
rightSum -= nums[i]
}
return -1
}
// -----------------------------------------------------------------------------
// 17. Given an array of integers nums, write a method that returns the "pivot" index of this array.
// We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
// If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
// pivotIndex([1, 7, 3, 6, 5, 6]) == 3
// pivotIndex([1, 2, 3]) == -1
// pivotIndex([2, 1, -1]) == 0
func pivotIndex(nums: [Int]) -> Int {
var leftSum = 0
reversed += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func pivotIndex(nums: [Int]) -> Int { // invalid redeclaration of 'pivotIndex(nums:)'
func monotonic(l: [Int]) -> Bool {
if l.count == 0 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count == 0 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
public func test_monotonic() {
print("\n\n")
print("monotonic")
print("=========")
print("monotonic([1, 2, 4, 20]) == true")
print(monotonic([1, 2, 4, 20]))
print("monotonic([1, 20, 4, 10]) == false")
print(monotonic([1, 20, 4, 10]))
print("monotonic([4, 1, 0, -10]) == true")
print(monotonic([4, 1, 0, -10]))
print("monotonic([]) == true")
print(monotonic([]))
print("monotonic([1]) == true")
print(monotonic([1]))
print("monotonic([1, 1]) == true")
print(monotonic([1, 1]))
print("monotonic([1, 1, 1]) == true")
print(monotonic([1, 1, 1]))
print("monotonic([1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]))
print("monotonic([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) == true")
print(monotonic([1, 1, 1, 1, 1,
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] < l[i-1] {
increasing = false
}
if l[i] > l[i-1] {
decreasing = false
}
}
return increasing || decreasing
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given two strings, write a method to decide if one is a permutation of the
// other.
//
// Example:
//
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPermutation("abcd", "dabc") == true
// isPerm
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
func swapCase(s: String) -> String {
return String(s.map { $0.isUpperCase() ? $0.lowerCase() : $0.upperCase() })
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Greetings!") == "!sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 4. Write a function that takes a string as input and returns the string with all lowercase characters changed to uppercase and vice versa.
// swapCase("Hello, World!") == "hELLO, wORLD!"
// swapCase("HELLO, WORLD!") == "hello, world!"
func swapCase(s: String) -> String {
return String(s.map { $0.isUpperCase() ? $0.lowerCase() : $0.upperCase() })
}
// 5. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 6. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 7. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 8. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 9. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
func countBits(n: Int) -> Int {
return String(n, radix: 2).filter { $0 == "1" }.count
}
// 10. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 100110100
return String(s.map { $0.isUpperCase() ? $0.lowerCase() : $0.upperCase() }) // value of type 'String.Element' (aka 'Character') has no member 'lowerCase'
return String(s.map { $0.isUpperCase() ? $0.lowerCase() : $0.upperCase() }) // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
return String(s.map { $0.isUpperCase() ? $0.lowerCase() : $0.upperCase() }) // value of type 'String.Element' (aka 'Character') has no member 'upperCase'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
for i in l1 {
if l2.contains(i) {
result.append(i)
}
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
for i in l1 {
if l2.contains(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.1
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// -----------------------------------------------------------------------------
// reverseString("hello") == "olleh"
// reverseString("hello world") == "dlrow olleh"
// reverseString("") == ""
// reverseString("a") == "a"
// reverseString("abc") == "cba"
// reverseString("abcdef") == "fedcba"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// -----------------------------------------------------------------------------
// twoSum([2, 7, 11, 15], 9) == [0, 1]
// twoSum([2, 7, 11, 15], 18) == [1, 2]
// twoSum([2, 7, 11, 15], 17) == [0, 2]
// twoSum([2, 7, 11, 15], 16) == [1, 3]
// twoSum([2, 7, 11, 15], 15) == [0, 3]
// twoSum([2, 7, 11, 15], 14) == [1, 3]
// twoSum([2, 7, 11, 15], 13) == [0, 3]
// twoSum([2, 7, 11, 15], 12) == [1, 3]
// twoSum([2, 7, 11, 15], 11) == [0, 3]
// twoSum([2, 7, 11, 15], 10) == [1, 3]
// twoSum([2, 7, 11, 15], 9) == [0, 3]
// twoSum([2, 7, 11, 15], 8) == [1, 3]
// twoSum([2, 7, 11, 15], 7) == [0, 3]
// twoSum([2, 7, 11, 15], 6) == [1, 3]
// twoSum([2, 7, 11, 15], 5) == [0, 3]
// twoSum([2, 7, 11, 15], 4) == [1, 3]
// twoSum([2, 7, 11, 15], 3) == [0, 3]
// twoSum([2, 7, 11, 15], 2) == [0
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
for i in l1 {
if l2.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
for i in l1 {
if l2.contains(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each duplicate removed.
// removeDuplicates("abcde") == "abcde"
// removeDuplicates("abcabc") == "abc"
// removeDuplicates("abbbc") == "ab"
// removeDuplicates("") == ""
// removeDuplicates("aabbcc") == "abc"
// removeDuplicates("aabbccddeff") == "abcdef"
// removeDuplicates("abcabcabc") == "abc"
// removeDuplicates("abcabcabcabc") == "abc"
// removeDuplicates("abcabcabcabcdefghijklmno") == "abcdefghijklmno"
// removeDuplicates("abcabcabcabcdefghijklmnoabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc") == "abcdefghijklmnoabc"
// removeDuplicates("abcabcabcabcdefghijklmnoabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc"
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
var l1Set = Set(l1)
for i in l2 {
if l1Set.contains(i) {
result.append(i)
}
}
return result
}
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = []
var l1Set = Set(l1)
for i in l2 {
if l1Set.contains(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
// removeVowels("I love learning Swift") == " lv lrnng Swtft"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all vowels removed.
// removeVowels("I love learning Swift") == " lv
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }
}
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }
}
// -----------------------------------------------------------------------------
// 1.2. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("") == ""
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 1.3. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("") == ""
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 1.4. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("") == ""
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 1.5. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("") == ""
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 1.6. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("") == ""
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 1.7. Write a function that takes a string and returns a new string with all
// the vowels removed.
// removeVowels("I am awesome") == "m wsm"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels(""
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // cannot use mutating member on immutable value: 'str' is a 'let' constant
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // missing argument label 'with:' in call
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // value of tuple type '()' has no member 'replace'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.sorted()
}
func reverse(s: String) -> String {
return String(s.reversed())
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
return l1.filter { l2.contains($0) }.sorted()
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
func reverse(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
func reverse(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// characters in reverse order.
// reverse("hello") == "
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
import Foundation
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
print(common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]))
print(common(l1: [5, 3, 2, 8], l2: [3, 2]))<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성민 on 2022/07/15.
//
import Foundation
var a = 10
var b = 20
var c = a + b
print(c)
var d = a - b
print(d)
var e = a * b
print(e)
var f = a / b
print(f)
var g = a % b
print(g)
var h = a ** b
print(h)
var i = a++
print(i)
var j = ++a
print(j)
var k = a--
print(k)
var l = --a
print(l)
var m = a == b
print(m)
var n = a != b
print(n)
var o = a > b
print(o)
var p = a < b
print(p)
var q = a >= b
print(q)
var r = a <= b
print(r)
var s = a && b
print(s)
var t = a || b
print(t)
var u = !a
print(u)
var v = a ?? b
print(v)
var w = a ?? 100
print(w)
var x = a ?? 100 ?? 200
print(x)
var y = a ?? 100 ?? 200 ?? 300
print(y)
var z = a ?? 100 ?? 200 ?? 300 ?? 400
print(z)
var aa = a ?? 100 ?? 200 ?? 300 ?? 400 ?? 500
print(aa)
var bb = a ?? 100 ?? 200 ?? 300 ?? 400 ?? 500 ?? 600
print(bb)
var cc = a ?? 100 ?? 200 ?? 300 ?? 400 ?? 500 ?? 600 ?? 700
print(cc)
var dd = a ?? 100 ?? 200 ?? 300 ?? 400 ?? 500 ?? 600 ?? 700 ?? 800
print(dd)
var ee = a ?? 100 ?? 200 ?? 300 ?? 400 ?? 500 ?? 600 ?? 700 ?? 800 ?? 900
print(ee)
var ff = a ?? 100 ?? 200 ?? 300
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// 2. 소수 판별
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
largest = i
} else {
i += 1
}
}
return n == 1 ? largest : n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
largest = i
} else {
i += 1
}
}
return n == 1 ? largest : n
}
// -----------------------------------------------------------------------------
// 14. Longest Collatz sequence
// -----------------------------------------------------------------------------
//
// The following iterative sequence is defined for the set of positive integers:
//
// n → n/2 (n is even)
// n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence:
//
// 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
//
// It can be seen that this sequence (starting at 13 and finishing at 1) contains
// 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
// that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
//
// -----------------------------------------------------------------------------
//
// 14. Longest Collatz sequence
// -----------------------------------------------------------------------------
//
// The following iterative sequence is defined for the set of positive integers:
//
// n → n/2 (n is even)
// n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence:
//
// 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
//
// It can be seen that this sequence (starting at 13 and finishing at 1) contains
// 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
// that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
//
// -----------------------------------------------------------------------------
//
// 14. Longest Collatz sequence
// -----------------------------------------------------------------------------
//
// The following iterative sequence is defined for the set of positive integers:
//
// n → n/2 (n is even)
// n → 3n + 1 (n is odd)
//
// Using the rule above and starting with 13, we generate the following sequence:
//
// 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
//
// It can be seen that this sequence (starting at 13 and finishing at 1) contains
// 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
// that all starting numbers finish at 1.
//
// Which starting number, under one million, produces the longest chain?
//
// NOTE: Once the chain starts the terms are allowed to go above one million.
//
// -----------------------------------------------------------------------------
//
// 14. Longest Collatz sequence
// -----------------------------------------------------------------------------
//
// The following iterative sequence is defined for the set of positive integers:
//
// n → n/2 (n is even)
// n → 3n + 1 (n is odd)
//
// Using the rule above and starting
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return n == 1 ? largest : n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return n == 1 ? largest : n
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrime = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrime = i
n /= i
} else {
i += 1
}
}
return largestPrime
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrime = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrime = i
n /= i
} else {
i += 1
}
}
return largestPrime
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
// 2.10
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
// 2.11
// Write a function that takes an integer as input and returns the number of bits that are equal to one in the binary representation of that number.
// The returned value should be between 0 and 32 (inclusive).
// Example:
// countBits(5) == 2
// countBits(0) == 0
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 2.12
// Write a function that takes an integer as input and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example:
// Example:
// countSetBits(0b00000000000000000000000000001011) == 3
// countSetBits(0b11111111111111111111111111111101) == 31
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 2.13
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number,
// ignoring the leading zeros.
// Example:
// Example:
// countSetBits(0b00000000000000000000000000001011) == 3
// countSetBits(0b11111111111111111111111111111101) == 31
// countSetBits(0b00000000000000000000000010000000) == 1
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 2.14
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number,
// ignoring the leading zeros.
// Example:
// Example:
// countSetBits(0b00000000000000000000000000001011) == 3
// countSetBits(0b11111111111111111111111111111101) == 31
// countSetBits(0b00000000000000000000000010000000) == 1
// countSetBits(0b00000000000000000000000000000000) == 0
func countSetBits(n: Int) -> Int {
var count = 0
while n > 0 {
count += n & 1
n >>= 1
}
return count
}
// 2.15
// Write a function that takes an
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
reversed += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
n /= i
} else {
i += 1
}
}
return largestPrimeFactor
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largestPrimeFactor = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largestPrimeFactor = i
n /= i
} else {
i += 1
}
}
return largestPrimeFactor
}
// 2. 소수 판별
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함수
// 소수 판별 함
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return largest
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of consonants
// in the string.
// A consonant is a letter that is not a, e, i, o, u, or y.
// For example, countConsonants("This is a test") == 4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns the number of vowels
// in the string.
// A vowel is an a, e, i, o, u, or y.
// For example, countVowels("This is a test") == 4
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number of words in
// the string.
// A word is a sequence of non-space characters.
// For example, countWords("This is a test") == 3
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns the number of uppercase
// letters in the string.
// For example, countUppercase("This is a test") == 2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns the number of lowercase
// letters in the string.
// For example, countLowercase("This is a test") == 5
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns the number of digits in
// the string.
// For example, countDigits("This is a test") == 0
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns the number of words that
// contain the letter "e".
// For example, countEWords("This is a test") == 1
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns the number of words that
// contain the letter "t".
// For example, countTWords("This is a test") == 2
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 18. Write a
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
for i in 2...n {
if n % i == 0 {
largest = i
while n % i == 0 {
n /= i
}
}
}
return largest
}
// 2.1
// 2.2
// 2.3
// 2.4
// 2.5
// 2.6
// 2.7
// 2.8
// 2.9
// 2.10
// 2.11
// 2.12
// 2.13
// 2.14
// 2.15
// 2.16
// 2.17
// 2.18
// 2.19
// 2.20
// 2.21
// 2.22
// 2.23
// 2.24
// 2.25
// 2.26
// 2.27
// 2.28
// 2.29
// 2.30
// 2.31
// 2.32
// 2.33
// 2.34
// 2.35
// 2.36
// 2.37
// 2.38
// 2.39
// 2.40
// 2.41
// 2.42
// 2.43
// 2.44
// 2.45
// 2.46
// 2.47
// 2.48
// 2.49
// 2.50
// 2.51
// 2.52
// 2.53
// 2.54
// 2.55
// 2.56
// 2.57
// 2.58
// 2.59
// 2.60
// 2.61
// 2.62
// 2.63
// 2.64
// 2.65
// 2.66
// 2.67
// 2.68
// 2.69
// 2.70
// 2.71
// 2.72
// 2.73
// 2.74
// 2.75
// 2.76
// 2.77
// 2.78
// 2.79
// 2.80
// 2.81
// 2.82
// 2.83
// 2.84
// 2.85
// 2.86
// 2.87
// 2.88
// 2.89
// 2.90
// 2.91
// 2.92
// 2.93
// 2.94
// 2.95
// 2.96
// 2.97
// 2.98
// 2.99
// 3.00
// 3.01
// 3.02
// 3.03
// 3.04
// 3.05
// 3.06
// 3.07
// 3.08
// 3.09
// 3.10
// 3.11
// 3.12
// 3.13
// 3.14
// 3.15
// 3.16
// 3.17
// 3.18
// 3.19
// 3.20
// 3.21
// 3.22
// 3.23
// 3.24
// 3.25
// 3.26
// 3.27
// 3.28
// 3.29
// 3.30
// 3.31
// 3.32
// 3.33
// 3.34
// 3.35
// 3.36
// 3.37
// 3.38
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return largest
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func factorial5(n: Int) -> Int {
var count = 0
var i = 5
while i <= n {
count += n / i
i *= 5
}
return count
}
func squareDigits(n: Int) -> Int {
var s = String(n)
var i = 0
while i < s.count {
s[i] = String(Int(s[i]!) * Int(s[i]!))[0]
i += 1
}
return Int(s)
}
func palindrome(s: String) -> Bool {
return s == String(s.reversed())
}
func vowelCount(s: String) -> Int {
var count = 0
var i = 0
while i < s.count {
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" {
count += 1
}
i += 1
}
return count
}
func letterCount(s: String) -> [String: Int] {
var dict = [String: Int]()
var i = 0
while i < s.count {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
i += 1
}
return dict
}
func letterCounts(s: String) -> [String: Int] {
var dict = [String: Int]()
var i = 0
while i < s.count {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
i += 1
}
return dict
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var largest = 1
var i = 2
while i * i <= n {
if n % i == 0 {
largest = i
n /= i
} else {
i += 1
}
}
return largest
}
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 11. Write a function that takes an integer and returns the number of 5s that appear in its factorial.
// factorial5(5) == 1
// factorial5(10) == 2
// factorial5(20) == 4
func factorial5(n: Int) -> Int {
var count = 0
var i = 5
while i <= n {
count += n / i
i *= 5
}
return count
}
// 12. Write a function that takes an integer and returns the number of digits in its square.
// squareDigits(9119) == 811181
func squareDigits(n: Int) -> Int {
var s = String(n)
var i = 0
while i < s.count {
s[i] = String(Int(s[i]!) * Int(s[i]!))[0]
i += 1
}
return Int(s)
}
// 13. Write a function that takes a string and returns true if the string is a palindrome, and false otherwise.
// palindrome("radar") == true
// palindrome("hello") == false
func palindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// 14. Write a function that takes a string and returns the number of vowels in the string.
// vowelCount("apple") == 2
// vowelCount("hello") == 1
func vowelCount(s: String) -> Int {
var count = 0
var i = 0
while i < s.count {
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" {
count += 1
}
i += 1
}
return count
}
// 15. Write a function that takes a string and returns the number of times a letter appears in the string.
// letterCount("apple") == {"a": 2, "p": 2, "l": 1, "e": 1}
// letterCount("hello") == {"h": 1, "e": 1, "l": 2, "o": 1}
func letterCount(s: String) -> [String: Int] {
var dict = [String: Int]()
var i = 0
while i < s.count {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
i += 1
}
return dict
}
// 16. Write a function that takes a string and returns the number of times each letter appears in the string.
// letterCounts("apple") == {"a": 2, "p": 2, "l": 1, "e": 1}
// letterCounts("hello") == {"h": 1, "e": 1, "l": 2, "o": 1}
func letterCounts(s: String) -> [String: Int] {
var dict = [String: Int]()
var i = 0
while i < s.count {
if dict[s[i]] == nil {
dict[s[i]] = 1
} else {
dict[s[i]]! += 1
}
i += 1
}
return dict
}
// 17
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n - 1)
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n - 1)
}
}
// 1. Write a function that takes a string and returns the number of vowels in the string.
// 2. Write a function that takes a string and returns the number of consonants in the string.
// 3. Write a function that takes a string and returns the number of words in the string.
// 4. Write a function that takes a string and returns the number of sentences in the string.
// 5. Write a function that takes a string and returns the number of uppercase letters in the string.
// 6. Write a function that takes a string and returns the number of lowercase letters in the string.
// 7. Write a function that takes a string and returns the number of digits in the string.
// 8. Write a function that takes a string and returns the number of whitespace characters in the string.
// 9. Write a function that takes a string and returns the number of words that start with a vowel in the string.
// 10. Write a function that takes a string and returns the number of words that end with a consonant in the string.
// 11. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 12. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 13. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 14. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 15. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 16. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 17. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 18. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 19. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 20. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 21. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 22. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 23. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 24. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 25. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 26. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 27. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 28. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 29. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 30. Write a function that takes a string and returns the number of words that start with a vowel or end with a consonant in the string.
// 31. Write a function that takes a string and returns the number of words that start with a
return n + sumToN(n - 1) // missing argument label 'n:' in call
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// vowelCount is a function that counts the number of vowels in a string.
// vowelCount("hello") == 2
// vowelCount("apple") == 2
// vowelCount("banana") == 3
// vowelCount("orange") == 2
// vowelCount("grape") == 1
// vowelCount("watermelon") == 3
// vowelCount("kiwi") == 1
// vowelCount("strawberry") == 4
// vowelCount("blueberry") == 4
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") == 2
// vowelCount("pineapple") == 5
// vowelCount("melon") == 2
// vowelCount("peach") == 2
// vowelCount("cherry") == 2
// vowelCount("pear") == 1
// vowelCount("plum") ==
return n + sumToN(n - 1) // missing argument label 'n:' in call
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
// 1. Write a function that takes a string and returns the number of vowels in the string.
// 2. Write a function that takes a string and returns the number of consonants in the string.
// 3. Write a function that takes a string and returns the number of words in the string.
// 4. Write a function that takes a string and returns the number of sentences in the string.
// 5. Write a function that takes a string and returns the number of uppercase letters in the string.
// 6. Write a function that takes a string and returns the number of lowercase letters in the string.
// 7. Write a function that takes a string and returns the number of digits in the string.
// 8. Write a function that takes a string and returns the number of whitespace characters in the string.
// 9. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 10. Write a function that takes a string and returns the number of words in the string.
// 11. Write a function that takes a string and returns the number of sentences in the string.
// 12. Write a function that takes a string and returns the number of uppercase letters in the string.
// 13. Write a function that takes a string and returns the number of lowercase letters in the string.
// 14. Write a function that takes a string and returns the number of digits in the string.
// 15. Write a function that takes a string and returns the number of whitespace characters in the string.
// 16. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 17. Write a function that takes a string and returns the number of words in the string.
// 18. Write a function that takes a string and returns the number of sentences in the string.
// 19. Write a function that takes a string and returns the number of uppercase letters in the string.
// 20. Write a function that takes a string and returns the number of lowercase letters in the string.
// 21. Write a function that takes a string and returns the number of digits in the string.
// 22. Write a function that takes a string and returns the number of whitespace characters in the string.
// 23. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 24. Write a function that takes a string and returns the number of words in the string.
// 25. Write a function that takes a string and returns the number of sentences in the string.
// 26. Write a function that takes a string and returns the number of uppercase letters in the string.
// 27. Write a function that takes a string and returns the number of lowercase letters in the string.
// 28. Write a function that takes a string and returns the number of digits in the string.
// 29. Write a function that takes a string and returns the number of whitespace characters in the string.
// 30. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 31. Write a function that takes a string and returns the number of words in the string.
// 32. Write a function that takes a string and returns the number of sentences in the string.
// 33. Write a function that takes a string and returns the number of uppercase letters in the string.
// 34. Write a function that takes a string and returns the number of lowercase letters in the string.
// 35. Write a function that takes a string and returns the number of digits in the string.
// 36. Write a function that takes a string and returns the number of whitespace characters in the string.
// 37. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 38. Write a function that takes a string and returns the number of words in the string.
// 39. Write a function that takes a string and returns the number of sentences in the string.
// 40. Write a function that takes a string and returns the number of uppercase letters in the string.
// 41. Write a function that takes a string
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
count += 1
}
}
return count
}
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// countVowels("Hello world") == 3
// countVowels("apple") == 2
// countVowels("a") == 1
// countVowels("") == 0
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 3. Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world") == 2
// countWords("apple") == 1
// countWords("a") == 1
// countWords("") == 0
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
// 4. Write a function that takes a string as input and returns the number of consonants in the string.
// countConsonants("Hello world") == 7
// countConsonants("apple") == 4
// countConsonants("a") == 0
// countConsonants("") == 0
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
count += 1
}
}
return count
}
// 5. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// countUppercase("Hello world") == 2
// countUppercase("apple") == 1
// countUppercase("a") == 0
// countUppercase("") == 0
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
// 6. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// countLowercase("Hello world") == 5
// countLowercase("apple") == 4
// countLowercase("a") == 1
// countLowercase("") == 0
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
// 7. Write a function that takes a string as input and returns the number of digits in the string.
// countDigits("Hello world") == 0
// countDigits("apple") == 1
// countDigits("a") == 0
// countDigits("") == 0
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
// 8. Write a function that takes a string as input and returns the number of words that start with a vowel.
// countWordsStartingWithVowel("Hello world") == 1
// countWordsStartingWithVowel("apple") == 1
// countWordsStartingWithVowel("a") == 1
// countWordsStartingWithVowel("") == 0
func countWordsStartingWithVowel(string: String
return n + sumToN(n - 1) // missing argument label 'n:' in call
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
// 1. Write a function that takes a string and returns the number of vowels in the string.
// 2. Write a function that takes a string and returns the number of consonants in the string.
// 3. Write a function that takes a string and returns the number of words in the string.
// 4. Write a function that takes a string and returns the number of sentences in the string.
// 5. Write a function that takes a string and returns the number of uppercase letters in the string.
// 6. Write a function that takes a string and returns the number of lowercase letters in the string.
// 7. Write a function that takes a string and returns the number of digits in the string.
// 8. Write a function that takes a string and returns the number of whitespace characters in the string.
// 9. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 10. Write a function that takes a string and returns the number of characters in the string.
// 11. Write a function that takes a string and returns the number of words in the string.
// 12. Write a function that takes a string and returns the number of sentences in the string.
// 13. Write a function that takes a string and returns the number of uppercase letters in the string.
// 14. Write a function that takes a string and returns the number of lowercase letters in the string.
// 15. Write a function that takes a string and returns the number of digits in the string.
// 16. Write a function that takes a string and returns the number of whitespace characters in the string.
// 17. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 18. Write a function that takes a string and returns the number of characters in the string.
// 19. Write a function that takes a string and returns the number of words in the string.
// 20. Write a function that takes a string and returns the number of sentences in the string.
// 21. Write a function that takes a string and returns the number of uppercase letters in the string.
// 22. Write a function that takes a string and returns the number of lowercase letters in the string.
// 23. Write a function that takes a string and returns the number of digits in the string.
// 24. Write a function that takes a string and returns the number of whitespace characters in the string.
// 25. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 26. Write a function that takes a string and returns the number of characters in the string.
// 27. Write a function that takes a string and returns the number of words in the string.
// 28. Write a function that takes a string and returns the number of sentences in the string.
// 29. Write a function that takes a string and returns the number of uppercase letters in the string.
// 30. Write a function that takes a string and returns the number of lowercase letters in the string.
// 31. Write a function that takes a string and returns the number of digits in the string.
// 32. Write a function that takes a string and returns the number of whitespace characters in the string.
// 33. Write a function that takes a string and returns the number of non-whitespace characters in the string.
// 34. Write a function that takes a string and returns the number of characters in the string.
// 35. Write a function that takes a string and returns the number of words in the string.
// 36. Write a function that takes a string and returns the number of sentences in the string.
// 37. Write a function that takes a string and returns the number of uppercase letters in the string.
// 38. Write a function that takes a string and returns the number of lowercase letters in the string.
// 39. Write a function that takes a string and returns the number of digits in the string.
// 40. Write a function that takes a string and returns the number of whitespace characters in the string.
// 41. Write a function that takes a string and returns the number of non-whitespace characters in
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// vowelCount is a function that counts the number of vowels in a string.
// vowelCount("hello") == 2
// vowelCount("apple") == 2
// vowelCount("banana") == 3
// vowelCount("orange") == 4
// vowelCount("grape") == 2
// vowelCount("watermelon") == 5
// vowelCount("kiwi") == 2
// vowelCount("strawberry") == 5
// vowelCount("blueberry") == 5
// vowelCount("peach") == 2
// vowelCount("cherry") == 3
// vowelCount("mango") == 3
// vowelCount("pear") == 2
// vowelCount("melon") == 3
// vowelCount("pineapple") == 5
// vowelCount("cranberry") == 5
// vowelCount("raspberry") == 5
// vowelCount("lemon") == 2
// vowelCount("kiwi") == 2
// vowelCount("strawberry") == 5
// vowelCount("blueberry") == 5
// vowelCount("peach") == 2
// vowelCount("cherry") == 3
// vowelCount("mango") == 3
// vowelCount("pear") == 2
// vowelCount("melon") == 3
// vowelCount("pineapple") == 5
// vowelCount("cranberry") == 5
// vowelCount("raspberry") == 5
// vowelCount("lemon") == 2
// vowelCount("kiwi") == 2
// vowelCount("strawberry") == 5
// vowelCount("blueberry") == 5
// vowelCount("peach") == 2
// vowelCount("cherry") == 3
// vowelCount("mango") == 3
// vowelCount("pear") == 2
// vowelCount("melon") == 3
// vowelCount("pineapple") == 5
// vowelCount("cranberry") == 5
// vowelCount("raspberry") == 5
// vowelCount("lemon") == 2
// vowelCount("kiwi") == 2
// vowelCount("strawberry") == 5
// vowelCount("blueberry") == 5
// vowelCount("peach") == 2
// vowelCount("cherry") == 3
// vowelCount("mango") == 3
// vowelCount("pear") == 2
// vowelCount("melon") == 3
// vowelCount("pineapple") == 5
// vowelCount("cranberry") == 5
// vowelCount("raspberry") == 5
// vowelCount("lemon") == 2
// vowelCount("kiwi") == 2
// vowelCount("strawberry") == 5
// vowelCount("blueberry") == 5
// vowelCount("peach") == 2
// vowelCount("cherry") == 3
// vowelCount("mango") == 3
// vowelCount("pear") == 2
// vowelCount("melon") == 3
// vowelCount("pineapple") == 5
// vowelCount("cranberry") == 5
// vowelCount("raspberry") == 5
// vowelCount("lemon") == 2
// vowelCount("kiwi") == 2
//
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
// 2. Write a function that takes a string and returns a string with the first letter capitalized.
// capitalize("hello") == "Hello"
// capitalize("cat") == "Cat"
// capitalize("") == ""
// capitalize("123") == "123"
// capitalize("12345") == "12345"
// capitalize("123456789") == "123456789"
// capitalize("1234567890") == "1234567890"
// capitalize("12345678901") == "12345678901"
// capitalize("123456789012") == "123456789012"
// capitalize("1234567890123") == "1234567890123"
// capitalize("12345678901234") == "12345678901234"
// capitalize("123456789012345") == "123456789012345"
// capitalize("1234567890123456") == "1234567890123456"
// capitalize("12345678901234567") == "12345678901234567"
// capitalize("123456789012345678") == "123456789012345678"
// capitalize("1234567890123456789") == "1234567890123456789"
// capitalize("12345678901234567890") == "12345678901234567890"
// capitalize("123456789012345678901") == "123456789012345678901"
// capitalize("1234567890123456789012" == "1234567890123456789012"
// capitalize("12345678901234567890123" == "12345678901234567890123"
// capitalize("123456789012345678901234" == "123456789012345678901234"
// capitalize("1234567890123456789012345" == "1234567890123456789012345"
// capitalize("12345678901234567890123456" == "12345678901234567890123456"
// capitalize("123456789012345678901234567" == "123456789012345678901234567"
// capitalize("123456789012345678
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
func sumOfNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sumOfNumbers(n: n - 1)
}
}
func sumOfEvenNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 2 == 0 {
return n + sumOfEvenNumbers(n: n - 1)
} else {
return sumOfEvenNumbers(n: n - 1)
}
}
}
func sumOfOddNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 2 == 1 {
return n + sumOfOddNumbers(n: n - 1)
} else {
return sumOfOddNumbers(n: n - 1)
}
}
}
func sumOfDivisibleNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 3 == 0 || n % 5 == 0 {
return n + sumOfDivisibleNumbers(n: n - 1)
} else {
return sumOfDivisibleNumbers(n: n - 1)
}
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
// 2. Write a function that takes a number as input and returns the factorial of that number.
// factorial(n: 5) == 120
// factorial(n: 10) == 3628800
// factorial(n: 1) == 1
// factorial(n: 0) == 1
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
// 3. Write a function that takes a number as input and returns the sum of all numbers from 1 to that number.
// sumOfNumbers(n: 5) == 15
// sumOfNumbers(n: 10) == 55
// sumOfNumbers(n: 1) == 1
// sumOfNumbers(n: 0) == 0
func sumOfNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sumOfNumbers(n: n - 1)
}
}
// 4. Write a function that takes a number as input and returns the sum of all even numbers from 1 to that number.
// sumOfEvenNumbers(n: 5) == 10
// sumOfEvenNumbers(n: 10) == 30
// sumOfEvenNumbers(n: 1) == 2
// sumOfEvenNumbers(n: 0) == 0
func sumOfEvenNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 2 == 0 {
return n + sumOfEvenNumbers(n: n - 1)
} else {
return sumOfEvenNumbers(n: n - 1)
}
}
}
// 5. Write a function that takes a number as input and returns the sum of all odd numbers from 1 to that number.
// sumOfOddNumbers(n: 5) == 9
// sumOfOddNumbers(n: 10) == 25
// sumOfOddNumbers(n: 1) == 1
// sumOfOddNumbers(n: 0) == 0
func sumOfOddNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 2 == 1 {
return n + sumOfOddNumbers(n: n - 1)
} else {
return sumOfOddNumbers(n: n - 1)
}
}
}
// 6. Write a function that takes a number as input and returns the sum of all numbers that are divisible by 3 or 5 from 1 to that number.
// sumOfDivisibleNumbers(n: 5) == 8
// sumOfDivisibleNumbers(n: 10) == 30
// sumOfDivisibleNumbers(n: 1) == 1
// sumOfDivisibleNumbers(n: 0) == 0
func sumOfDivisibleNumbers(n: Int) -> Int {
if n == 0 {
return 0
} else {
if n % 3 == 0 || n % 5 == 0 {
return n + sumOfDivisibleNumbers(n: n - 1)
} else {
return sumOfDivisibleNumbers(n: n - 1)
}
}
}
// 7. Write a function that takes a number as input and returns the sum of all numbers that are divisible by 3 or 5 from 1 to that number.
// sumOfDivisibleNumbers(n: 5) == 8
// sumOfDivisibleNumbers(n: 10) == 30
// sumOfDivisibleNumbers(n: 1) == 1
// sumOfDivisibleNumbers(n: 0) == 0
func
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func sumArray(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func charCount(string: String, char: String) -> Int {
var count = 0
for char in string {
if char == char {
count += 1
}
}
return count
}
func maxArray(numbers: [Int]) -> Int {
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
}
return max
}
func minArray(numbers: [Int]) -> Int {
var min = numbers[0]
for number in numbers {
if number < min {
min = number
}
}
return min
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// vowelCount is a function that counts the number of vowels in a string.
// vowelCount("Hello") == 2
// vowelCount("apple") == 2
// vowelCount("a") == 1
// vowelCount("") == 0
func vowelCount(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 3. Write a function that takes an array of numbers and returns the sum of the numbers.
// sumArray is a function that sums the numbers in an array.
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([10, 20, 30, 40, 50]) == 150
// sumArray([100, 200, 300, 400, 500]) == 1500
func sumArray(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// 4. Write a function that takes a string and returns the number of times a specific character appears in the string.
// charCount is a function that counts the number of times a specific character appears in a string.
// charCount("Hello", "l") == 2
// charCount("apple", "p") == 2
// charCount("a", "a") == 1
// charCount("", "a") == 0
func charCount(string: String, char: String) -> Int {
var count = 0
for char in string {
if char == char {
count += 1
}
}
return count
}
// 5. Write a function that takes an array of numbers and returns the maximum value in the array.
// maxArray is a function that finds the maximum value in an array of numbers.
// maxArray([1, 2, 3, 4, 5]) == 5
// maxArray([10, 20, 30, 40, 50]) == 50
// maxArray([100, 200, 300, 400, 500]) == 500
func maxArray(numbers: [Int]) -> Int {
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
}
return max
}
// 6. Write a function that takes an array of numbers and returns the minimum value in the array.
// minArray is a function that finds the minimum value in an array of numbers.
// minArray([1, 2, 3, 4, 5]) == 1
// minArray([10, 20, 30, 40, 50]) == 10
// minArray([100, 200, 300, 400, 500]) == 100
func minArray(numbers: [Int]) -> Int {
var min = numbers[0]
for number in numbers {
if number < min {
min = number
}
}
return min
}
// 7. Write a function that takes an array of numbers and returns the average value in the array.
// avgArray is a function that calculates the average value in an array of numbers.
// avgArray([1, 2, 3, 4, 5]) == 3
// avgArray([10, 20, 30, 40, 50]) == 25
// avgArray([100, 200, 300, 400, 500]) == 2
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
// 1. Write a function that takes a string and returns the number of vowels in the string.
// 2. Write a function that takes a string and returns the number of consonants in the string.
// 3. Write a function that takes a string and returns the number of words in the string.
// 4. Write a function that takes a string and returns the number of sentences in the string.
// 5. Write a function that takes a string and returns the number of uppercase letters in the string.
// 6. Write a function that takes a string and returns the number of lowercase letters in the string.
// 7. Write a function that takes a string and returns the number of digits in the string.
// 8. Write a function that takes a string and returns the number of whitespace characters in the string.
// 9. Write a function that takes a string and returns the number of characters in the string.
// 10. Write a function that takes a string and returns the number of words in the string.
// 11. Write a function that takes a string and returns the number of sentences in the string.
// 12. Write a function that takes a string and returns the number of uppercase letters in the string.
// 13. Write a function that takes a string and returns the number of lowercase letters in the string.
// 14. Write a function that takes a string and returns the number of digits in the string.
// 15. Write a function that takes a string and returns the number of whitespace characters in the string.
// 16. Write a function that takes a string and returns the number of characters in the string.
// 17. Write a function that takes a string and returns the number of words in the string.
// 18. Write a function that takes a string and returns the number of sentences in the string.
// 19. Write a function that takes a string and returns the number of uppercase letters in the string.
// 20. Write a function that takes a string and returns the number of lowercase letters in the string.
// 21. Write a function that takes a string and returns the number of digits in the string.
// 22. Write a function that takes a string and returns the number of whitespace characters in the string.
// 23. Write a function that takes a string and returns the number of characters in the string.
// 24. Write a function that takes a string and returns the number of words in the string.
// 25. Write a function that takes a string and returns the number of sentences in the string.
// 26. Write a function that takes a string and returns the number of uppercase letters in the string.
// 27. Write a function that takes a string and returns the number of lowercase letters in the string.
// 28. Write a function that takes a string and returns the number of digits in the string.
// 29. Write a function that takes a string and returns the number of whitespace characters in the string.
// 30. Write a function that takes a string and returns the number of characters in the string.
// 31. Write a function that takes a string and returns the number of words in the string.
// 32. Write a function that takes a string and returns the number of sentences in the string.
// 33. Write a function that takes a string and returns the number of uppercase letters in the string.
// 34. Write a function that takes a string and returns the number of lowercase letters in the string.
// 35. Write a function that takes a string and returns the number of digits in the string.
// 36. Write a function that takes a string and returns the number of whitespace characters in the string.
// 37. Write a function that takes a string and returns the number of characters in the string.
// 38. Write a function that takes a string and returns the number of words in the string.
// 39. Write a function that takes a string and returns the number of sentences in the string.
// 40. Write a function that takes a string and returns the number of uppercase letters in the string.
// 41. Write a function that takes a string and returns the number of lowercase letters in the string.
// 42. Write a function that takes a string
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func repeatedLetters(text: String) -> String {
var words = text.split(separator: " ")
var repeatedLetters = [String]()
var repeatedLettersCount = [Int]()
for word in words {
var repeatedLettersCountForWord = 0
var repeatedLettersForWord = [Character]()
for letter in word {
if repeatedLettersForWord.contains(letter) {
repeatedLettersCountForWord += 1
} else {
repeatedLettersForWord.append(letter)
}
}
repeatedLetters.append(word)
repeatedLettersCount.append(repeatedLettersCountForWord)
}
var maxRepeatedLettersCount = repeatedLettersCount[0]
var indexOfMaxRepeatedLettersCount = 0
for i in 1..<repeatedLettersCount.count {
if repeatedLettersCount[i] > maxRepeatedLettersCount {
maxRepeatedLettersCount = repeatedLettersCount[i]
indexOfMaxRepeatedLettersCount = i
}
}
return repeatedLetters[indexOfMaxRepeatedLettersCount]
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// 2.
// Given a string of text, return the first word with the greatest number of repeated letters.
// If there are multiple words that have the greatest number of repeated letters, return the first one.
// repeatedLetters("hello world") == "hello"
// repeatedLetters("a a a a b b b b") == "b"
// repeatedLetters("a a a a b b b b c c c c") == "c"
func repeatedLetters(text: String) -> String {
var words = text.split(separator: " ")
var repeatedLetters = [String]()
var repeatedLettersCount = [Int]()
for word in words {
var repeatedLettersCountForWord = 0
var repeatedLettersForWord = [Character]()
for letter in word {
if repeatedLettersForWord.contains(letter) {
repeatedLettersCountForWord += 1
} else {
repeatedLettersForWord.append(letter)
}
}
repeatedLetters.append(word)
repeatedLettersCount.append(repeatedLettersCountForWord)
}
var maxRepeatedLettersCount = repeatedLettersCount[0]
var indexOfMaxRepeatedLettersCount = 0
for i in 1..<repeatedLettersCount.count {
if repeatedLettersCount[i] > maxRepeatedLettersCount {
maxRepeatedLettersCount = repeatedLettersCount[i]
indexOfMaxRepeatedLettersCount = i
}
}
return repeatedLetters[indexOfMaxRepeatedLettersCount]
}
// 3.
// Given a string of text, return the first word with the greatest number of repeated letters.
// If there are multiple words that have the greatest number of repeated letters, return the first one.
// repeatedLetters("hello world") == "hello"
// repeatedLetters("a a a a b b b b") == "b"
// repeatedLetters("a a a a b b b b c c c c") == "c"
func repeatedLetters(text: String) -> String {
var words = text.split(separator: " ")
var repeatedLetters = [String]()
var repeatedLettersCount = [Int]()
for word in words {
var repeatedLettersCountForWord = 0
var repeatedLettersForWord = [Character]()
for letter in word {
if repeatedLettersForWord.contains(letter) {
repeatedLettersCountForWord += 1
} else {
repeatedLettersForWord.append(letter)
}
}
repeatedLetters.append(word)
repeatedLettersCount.append(repeatedLettersCountForWord)
}
var maxRepeatedLettersCount = repeatedLettersCount[0]
var indexOfMaxRepeatedLettersCount = 0
for i in 1..<repeatedLettersCount.count {
if repeatedLettersCount[i] > maxRepeatedLettersCount {
maxRepeatedLettersCount = repeatedLettersCount[i]
indexOfMaxRepeatedLettersCount = i
}
}
return repeatedLetters[indexOfMaxRepeatedLettersCount]
}
// 4.
// Given a string of text, return the first word with the greatest number of repeated letters.
// If there are multiple words that have the greatest number of repeated letters, return the first one.
// repeatedLetters("hello world") == "hello"
// repeatedLetters("a a a a b b b b") == "b"
// repeatedLetters("a a a a b b b b c c c c") == "c"
func repeatedLetters(text: String) -> String {
var words = text.split(separator: " ")
var repeatedLetters = [String]()
var repeatedLettersCount = [Int]()
stack.pop() // value of type '[Character]' has no member 'pop'
repeatedLetters.append(word) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func reverseString(s: String) -> String {
var reversed = ""
for char in s {
reversed = char + reversed
}
return reversed
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("ab") == "ba"
// reverseString("abc") == "cba"
// reverseString("abcd") == "dcba"
// reverseString("abcde") == "edcba"
func reverseString(s: String) -> String {
var reversed = ""
for char in s {
reversed = char + reversed
}
return reversed
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string with
// all capital letters converted to lowercase letters, and vice versa.
// swapCase("Hello, World!") == "hELLO, wORLD!"
// swapCase("HELLO, WORLD!") == "hello, world!"
// swapCase("") == ""
// swapCase("a") == "A"
// swapCase("A") == "a"
// swapCase("aBc") == "AbC"
// swapCase("AbC") == "aBC"
// swapCase("AbCd") == "aBCd"
// swapCase("AbCdEf") == "aBCdEf"
// swapCase("AbCdEfGh") == "aBCdEfgh"
// swapCase("AbCdEfGhIj") == "aBCdEfghIJ"
// swapCase("AbCdEfGhIjKl") == "aBCdEfghIJKL"
// swapCase("AbCdEfGhIjKlMn") == "aBCdEfghIJKLmN"
// swapCase("AbCdEfGhIjKlMnNoPqRsTuVwXyZ") == "aBCdEfghIJKLmNnOPQRSTUVWXYZ"
// swapCase("AbCdEfGhIjKlMnNoPqRsTuVwXyZ!@#$%^&*()") == "aBCdEfghIJKLmNnOPQRSTUVWXYZ!@#$%^&*()"
// swapCase("AbCdEfGhIjKlMnNoPqRsTuVwXyZ!@#$%^&*()-=_+") == "aBCdEfghIJKLmNnOPQRSTUVWXYZ!@#$%^&*()-=_+"
// swapCase("AbCdEfGhIjKlMnNoPqRsTuVwXyZ!@#$%^&*()-=_+{|}") == "aBCdEfghIJKLmNnOPQRSTUVWXYZ!@#$%^&*()-=_+{|}"
// swapCase("AbCdEfGhIjKlMnNoPqRsTuVwXyZ!@#$%^&*()-=_+{|}~") == "aBCdEfghIJKLmNnOPQRSTUVWXYZ!@#$%^&*()-=_+{|}~"
// swapCase("AbCdEfGhIjKlMnNo
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countSubstring(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive)
if index != nil {
count += 1
index += substring.count
} else {
break
}
}
return count
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the number of
// vowels in the string.
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the number of
// times the string appears in the string.
// countSubstring("Hello world", "llo") == 2
// countSubstring("Hello world", "lo") == 2
// countSubstring("Hello world", "world") == 1
// countSubstring("Hello world", "") == 1
func countSubstring(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive)
if index != nil {
count += 1
index += substring.count
} else {
break
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the number of
// times the string appears in the string.
// countSubstring("Hello world", "llo") == 2
// countSubstring("Hello world", "lo") == 2
// countSubstring("Hello world", "world") == 1
// countSubstring("Hello world", "") == 1
func countSubstring(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive)
if index != nil {
count += 1
index += substring.count
} else {
break
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the number of
// times the string appears in the string.
// countSubstring("Hello world", "llo") == 2
// countSubstring("Hello world", "lo") == 2
// countSubstring("Hello world", "world") == 1
// countSubstring("Hello world", "") == 1
func countSubstring(string: String, substring: String) -> Int {
var count = 0
var index = 0
while index < string.count {
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive)
if index != nil {
count += 1
index += substring.count
} else {
break
}
}
return count
}
// ---------------------------------------------------------
stack.pop() // value of type '[Character]' has no member 'pop'
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive) // cannot assign value of type 'String.Index?' to type 'Int'
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive) // extra arguments at positions #2, #3 in call
index = string.index(of: substring, range: (index, string.count - index), options: .caseInsensitive) // cannot infer contextual base in reference to member 'caseInsensitive'
if index != nil { // comparing non-optional value of type 'Int' to 'nil' always returns true
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// 2. Write a function that takes a string of brackets and determines if the brackets are balanced.
// The function should return true if the brackets are balanced and false if they are not.
// The brackets are balanced if for every opening bracket, there is a closing bracket.
// The brackets must be closed in the correct order.
// The brackets must also be matched with the correct order.
// The function should return false if the brackets are not balanced.
// balancedBrackets(brackets: "()") == true
// balancedBrackets(brackets: ")(()") == false
// balancedBrackets(brackets: "(()())") == true
// balancedBrackets(brackets: "(()))") == false
// balancedBrackets(brackets: "(()))(") == false
// balancedBrackets(brackets: "(()))((") == false
// balancedBrackets(brackets: "(()))((()") == false
// balancedBrackets(brackets: "(()))((())") == true
// balancedBrackets(brackets: "(()))((())(") == false
// balancedBrackets(brackets: "(()))((())(()") == false
// balancedBrackets(brackets: "(()))((())(())") == true
// balancedBrackets(brackets: "(()))((())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())") == true
// balancedBrackets(brackets: "(()))((())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())") == true
// balancedBrackets(brackets: "(()))((())(())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())") == true
// balancedBrackets(brackets: "(()))((())(())(())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())") == true
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())") == true
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(())(") == false
// balancedBrackets(brackets: "(()))((())(())(())(())(())(())(())(())(()") == false
// balancedBrackets(brackets: "(()))((())(()
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func vowelsInString(string: String) -> Int {
var vowels = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
func wordsInString(string: String) -> Int {
var words = 0
var currentWord = ""
for char in string {
if char == " " {
words += 1
currentWord = ""
} else {
currentWord += char
}
}
if currentWord != "" {
words += 1
}
return words
}
func consonantsInString(string: String) -> Int {
var consonants = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
return consonants
}
func uppercaseInString(string: String) -> Int {
var uppercase = 0
for char in string {
if char == char.uppercase {
uppercase += 1
}
}
return uppercase
}
func lowercaseInString(string: String) -> Int {
var lowercase = 0
for char in string {
if char == char.lowercase {
lowercase += 1
}
}
return lowercase
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number of vowels in the string.
// vowelsInString("Hello world") == 3
// vowelsInString("aeiou") == 5
// vowelsInString("") == 0
func vowelsInString(string: String) -> Int {
var vowels = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns the number of words in the string.
// wordsInString("Hello world") == 2
// wordsInString("") == 0
// wordsInString("Hello world, how are you?") == 4
func wordsInString(string: String) -> Int {
var words = 0
var currentWord = ""
for char in string {
if char == " " {
words += 1
currentWord = ""
} else {
currentWord += char
}
}
if currentWord != "" {
words += 1
}
return words
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns the number of consonants in the string.
// consonantsInString("Hello world") == 5
// consonantsInString("aeiou") == 0
// consonantsInString("") == 0
func consonantsInString(string: String) -> Int {
var consonants = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
consonants += 1
}
}
return consonants
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns the number of uppercase letters in the string.
// uppercaseInString("Hello world") == 1
// uppercaseInString("") == 0
// uppercaseInString("Hello world, how are you?") == 2
func uppercaseInString(string: String) -> Int {
var uppercase = 0
for char in string {
if char == char.uppercase {
uppercase += 1
}
}
return uppercase
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns the number of lowercase letters in the string.
// lowercaseInString("Hello world") == 5
// lowercaseInString("") == 0
// lowercaseInString("Hello world, how are you?") == 11
func lowercaseInString(string: String) -> Int {
var lowercase = 0
for char in string {
if char == char.lowercase {
lowercase += 1
}
}
return lowercase
}
// ---------------------------------------------------------------------------
stack.pop() // value of type '[Character]' has no member 'pop'
currentWord += char // cannot convert value of type 'Character' to expected argument type 'String'
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
switch bracket {
case "(":
stack.append(bracket)
case ")":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func isIsomorphic(s: String, t: String) -> Bool {
return isIsomorphicHelper(s, t) && isIsomorphicHelper(t, s)
}
func isIsomorphicHelper(s: String, t: String) -> Bool {
var map = [Character: Character]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = t[i]
} else if map[s[i]] != t[i] {
return false
}
}
return true
}
func isPalindrome(s: String) -> Bool {
var s = s.trim().toLowerCase()
var i = 0
var j = s.count - 1
while i < j {
if !isAlphaNumeric(s[i]) {
i++
} else if !isAlphaNumeric(s[j]) {
j--
} else if s[i] != s[j] {
return false
} else {
i++
j--
}
}
return true
}
func isAlphaNumeric(c: Character) -> Bool {
return (c >= "a" && c <= "z") || (c >= "0" && c <= "9")
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
switch bracket {
case "(":
stack.append(bracket)
case ")":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 1.1
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Given two strings s and t, determine if they are isomorphic.
// Two strings are isomorphic if the characters in s can be replaced to get t.
// All occurrences of a character must be replaced with another character while
// preserving the order of characters. No two characters may map to the same
// character but a character may map to itself.
// Example 1:
// Input: s = "egg", t = "add"
// Output: true
// Example 2:
// Input: s = "foo", t = "bar"
// Output: false
// Example 3:
// Input: s = "paper", t = "title"
// Output: true
// Note:
// You may assume both s and t have the same length.
func isIsomorphic(s: String, t: String) -> Bool {
return isIsomorphicHelper(s, t) && isIsomorphicHelper(t, s)
}
func isIsomorphicHelper(s: String, t: String) -> Bool {
var map = [Character: Character]()
for i in 0..<s.count {
if map[s[i]] == nil {
map[s[i]] = t[i]
} else if map[s[i]] != t[i] {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Example 1:
// Input: "A man, a plan, a canal: Panama"
// Output: true
// Example 2:
// Input: "race a car"
// Output: false
func isPalindrome(s: String) -> Bool {
var s = s.trim().toLowerCase()
var i = 0
var j = s.count - 1
while i < j {
if !isAlphaNumeric(s[i]) {
i++
} else if !isAlphaNumeric(s[j]) {
j--
} else if s[i] != s[j] {
return false
} else {
i++
j--
}
}
return true
}
func isAlphaNumeric(c: Character) -> Bool {
return (c >= "a" && c <= "z") || (c >= "0" && c <= "9")
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Given an input string, reverse the string word by word.
// A word is defined as a sequence of
stack.pop() // value of type '[Character]' has no member 'pop'
return isIsomorphicHelper(s, t) && isIsomorphicHelper(t, s) // missing argument labels 's:t:' in call
return isIsomorphicHelper(s, t) && isIsomorphicHelper(t, s) // missing argument labels 's:t:' in call
if map[s[i]] == nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
map[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if map[s[i]] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if map[s[i]] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
var s = s.trim().toLowerCase() // value of type 'String' has no member 'trim'
if !isAlphaNumeric(s[i]) { // missing argument label 'c:' in call
i++ // cannot find operator '++' in scope; did you mean '+= 1'?
} else if !isAlphaNumeric(s[j]) { // missing argument label 'c:' in call
j-- // cannot find operator '--' in scope; did you mean '-= 1'?
i++ // cannot find operator '++' in scope; did you mean '+= 1'?
j-- // cannot find operator '--' in scope; did you mean '-= 1'?
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b") == "b a"
// reverseString("a b c") == "c b a"
// reverseString("a b c d") == "d c b a"
// reverseString("a b c d e") == "e d c b a"
// reverseString("a b c d e f") == "f e d c b a"
// reverseString("a b c d e f g") == "g f e d c b a"
// reverseString("a b c d e f g h") == "h g f e d c b a"
// reverseString("a b c d e f g h i") == "i h g f e d c b a"
// reverseString("a b c d e f g h i j") == "j i h g f e d c b a"
// reverseString("a b c d e f g h i j k") == "k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l") == "l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m") == "m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n") == "n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o") == "o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p") == "p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q") == "q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r") == "r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s") == "s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t") == "t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u") == "u t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v") == "v w u t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v w") == "w x v t s r q p o n m l k j i h g f e d c b a"
// reverseString("a b c d e f g h i j k l m n
stack.pop() // value of type '[Character]' has no member 'pop'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
} else {
stack.pop()
}
}
}
return stack.isEmpty()
}
func countVowels(input: String) -> Int {
var count = 0
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(input: String) -> Int {
var count = 0
for char in input {
if char == " " {
count += 1
}
}
return count + 1
}
func countSentences(input: String) -> Int {
var count = 0
for char in input {
if char == "." {
count += 1
}
}
return count
}
func countParagraphs(input: String) -> Int {
var count = 0
for char in input {
if char == "\n" {
count += 1
}
}
return count
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
} else {
stack.pop()
}
}
}
return stack.isEmpty()
}
// 1.1.2
// Write a function that takes a string as input and returns the number of vowels in the string.
// countVowels("Hello world") == 3
// countVowels("I love cats") == 4
// countVowels("I love dogs") == 3
// countVowels("I love birds") == 4
// countVowels("I love birds and cats") == 8
func countVowels(input: String) -> Int {
var count = 0
for char in input {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 1.1.3
// Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world") == 2
// countWords("I love cats") == 2
// countWords("I love dogs") == 2
// countWords("I love birds") == 2
// countWords("I love birds and cats") == 4
func countWords(input: String) -> Int {
var count = 0
for char in input {
if char == " " {
count += 1
}
}
return count + 1
}
// 1.1.4
// Write a function that takes a string as input and returns the number of sentences in the string.
// countSentences("Hello world. I love cats.") == 2
// countSentences("I love dogs. I love cats.") == 2
// countSentences("I love birds. I love cats.") == 2
// countSentences("I love birds and cats.") == 1
// countSentences("I love birds and cats. I love cats.") == 2
func countSentences(input: String) -> Int {
var count = 0
for char in input {
if char == "." {
count += 1
}
}
return count
}
// 1.1.5
// Write a function that takes a string as input and returns the number of paragraphs in the string.
// countParagraphs("Hello world. I love cats.") == 1
// countParagraphs("I love dogs. I love cats.") == 1
// countParagraphs("I love birds. I love cats.") == 1
// countParagraphs("I love birds and cats.") == 1
// countParagraphs("I love birds and cats. I love cats.") == 2
func countParagraphs(input: String) -> Int {
var count = 0
for char in input {
if char == "\n" {
count += 1
}
}
return count
}
// 1.1.6
// Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world. I love cats.") == 2
// countWords("I love dogs. I love cats.") == 2
// countWords("I love birds. I love cats.") == 2
// countWords("I love birds and cats.") == 2
// countWords("I love birds and cats. I love cats.") == 2
func countWords(input: String) -> Int {
var count = 0
for char in input {
if char == " " {
count += 1
}
}
return count + 1
}
// 1.1.7
// Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello world. I love
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount == notCount
}
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount > notCount
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// 1.1.2
// Given a string, return true if the number of appearances of "is" anywhere in the
// string is equal to the number of appearances of "not" anywhere in the string (case sensitive).
// isNotIsNot("not not is not") == true
// isNotIsNot("is is not not") == false
// isNotIsNot("is is not is not") == false
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount == notCount
}
// 1.1.3
// Given a string, return true if the number of appearances of "is" anywhere in the
// string is greater than the number of appearances of "not" anywhere in the string (case sensitive).
// isNotIsNot("not not is not") == true
// isNotIsNot("is is not not") == false
// isNotIsNot("is is not is not") == true
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount > notCount
}
// 1.1.4
// Given a string, return true if the number of appearances of "is" anywhere in the
// string is greater than the number of appearances of "not" anywhere in the string (case sensitive).
// isNotIsNot("not not is not") == true
// isNotIsNot("is is not not") == false
// isNotIsNot("is is not is not") == true
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount > notCount
}
// 1.1.5
// Given a string, return true if the number of appearances of "is" anywhere in the
// string is greater than the number of appearances of "not" anywhere in the string (case sensitive).
// isNotIsNot("not not is not") == true
// isNotIsNot("is is not not") == false
// isNotIsNot("is is not is not") == true
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount > notCount
}
// 1.1.6
// Given a string, return true if the number of appearances of "is" anywhere in the
// string is greater than the number of appearances of "not" anywhere in the string (case sensitive).
// isNotIsNot("not not is not") == true
// isNotIsNot("is is not not") == false
// isNotIsNot("is is not is not") == true
func isNotIsNot(input: String) -> Bool {
var isCount = 0
var notCount = 0
for char in input {
if char == "is" {
isCount += 1
} else if char == "not" {
notCount += 1
}
}
return isCount > notCount
}
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
if char == "is" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == "not" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func isNotIsNot(input: String) -> Bool { // invalid redeclaration of 'isNotIsNot(input:)'
if char == "is" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
} else if char == "not" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coefficients = coefficients
}
func derivative() -> Polynomial {
return Polynomial(coefficients: derivative(xs: coefficients))
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coefficients = coefficients
}
func derivative() -> Polynomial {
return Polynomial(coefficients: derivative(xs: coefficients))
}
}
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coefficients = coefficients
}
func derivative() -> Polynomial {
return Polynomial(coefficients: derivative(xs: coefficients))
}
}
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coefficients = coefficients
}
func derivative() -> Polynomial {
return Polynomial(coefficients: derivative(xs: coefficients))
}
}
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coefficients = coefficients
}
func derivative() -> Polynomial {
return Polynomial(coefficients: derivative(xs: coefficients))
}
}
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Polynomial {
var coefficients: [Int]
init(coefficients: [Int]) {
self.coe
return Polynomial(coefficients: derivative(xs: coefficients)) // use of 'derivative' refers to instance method rather than global function 'derivative(xs:)' in module 'Solution'
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
print(derivative([3, 1, 2, 4, 5]))
print(derivative([1, 2, 3]))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
func alphabetize(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted()
for char in sortedChars {
result += char
}
return result
}
func reverseAlphabetize(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted(by: <)
for char in sortedChars {
result += char
}
return result
}
func removeDuplicates(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted()
for char in sortedChars {
if !result.contains(char) {
result += char
}
}
return result
}
func reverseRemoveDuplicates(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted(by: >)
for char in sortedChars {
if !result.contains(char) {
result += char
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
// 1. Write a function that takes a string and returns a string with all the letters in alphabetical order.
// Example: alphabetize("hello") == "ehllo"
// alphabetize("edabit") == "abdeit"
// alphabetize("") == ""
// alphabetize("sama") == "amass"
// alphabetize("c") == "c"
func alphabetize(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted()
for char in sortedChars {
result += char
}
return result
}
// 2. Write a function that takes a string and returns a string with all the letters in reverse alphabetical order.
// Example: reverseAlphabetize("hello") == "olleh"
// reverseAlphabetize("edabit") == "tibade"
// reverseAlphabetize("") == ""
// reverseAlphabetize("sama") == "assam"
// reverseAlphabetize("c") == "c"
func reverseAlphabetize(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted(by: <)
for char in sortedChars {
result += char
}
return result
}
// 3. Write a function that takes a string and returns a string with all the letters in alphabetical order, but with any duplicate letters removed.
// Example: removeDuplicates("hello") == "helo"
// removeDuplicates("edabit") == "abdeit"
// removeDuplicates("") == ""
// removeDuplicates("sama") == "amass"
// removeDuplicates("c") == "c"
func removeDuplicates(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted()
for char in sortedChars {
if !result.contains(char) {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a string with all the letters in reverse alphabetical order, but with any duplicate letters removed.
// Example: reverseRemoveDuplicates("hello") == "olleh"
// reverseRemoveDuplicates("edabit") == "tibade"
// reverseRemoveDuplicates("") == ""
// reverseRemoveDuplicates("sama") == "assam"
// reverseRemoveDuplicates("c") == "c"
func reverseRemoveDuplicates(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted(by: >)
for char in sortedChars {
if !result.contains(char) {
result += char
}
}
return result
}
// 5. Write a function that takes a string and returns a string with all the letters in alphabetical order, but with any duplicate letters removed.
// Example: removeDuplicates("hello") == "helo"
// removeDuplicates("edabit") == "abdeit"
// removeDuplicates("") == ""
// removeDuplicates("sama") == "amass"
// removeDuplicates("c") == "c"
func removeDuplicates(s: String) -> String {
var result = String()
var chars = Array(s)
var sortedChars = chars.sorted()
for char in sortedChars {
if !result.contains(char) {
result += char
}
}
return result
}
// 6
result += char // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += char // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += char // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += char // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
print(derivative([3, 1, 2, 4, 5]))
print(derivative([1, 2, 3]))
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
var xs = [3, 1, 2, 4, 5]
var result = derivative(xs: xs)
print("result: \(result)")
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// 2.
// Given a string, return the length of the longest substring without repeating characters.
// Example 1:
// Input: "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// 3.
// Given a string s, find the length of the longest substring without repeating characters.
// Example 1:
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: s = "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: s = "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// 4.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 5.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 6.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 7.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 8.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 9.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
// 10.
// Given a string s, find the longest palindromic substring in s.
// You may assume that
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count {
if i == 0 {
result.append(xs[i])
} else {
result.append(xs[i] * i)
}
}
return result
}
print(derivative([3, 1, 2, 4, 5]))
print(derivative([1, 2, 3]))
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
// 10. Write a function that takes a string and returns the number of vowels in the string.
// You may assume the input is guaranteed to be a string.
// You may iterate through the string as many times as necessary.
// You may not use any built-in string methods.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the `charCodeAt` method on strings.
// You may use the `toLowerCase` method on strings.
// You may use the `toUpperCase` method on strings.
// You may use the `split` method on strings.
// You may use the `join` method on strings.
// You may use the `indexOf` method on strings.
// You may use the `charAt` method on strings.
// You may use the `length` property on strings.
// You may use the
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Example:
// countVowels("Hello") == 2
// countVowels("Why do you ask?") == 4
// countVowels("Why?") == 0
// countVowels("") == 0
// countVowels("aeiou") == 5
// countVowels("aeiouaeiou") == 10
// countVowels("aeiouaeiouaeiouaeiou") == 15
// countVowels("aeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaei
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
print(fibfib(1)) // 0
print(fibfib(5)) // 4
print(fibfib(8)) // 24
print(fibfib(10)) // 41
print(fibfib(100)) // 354224848179261915075
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
// Please write a function that takes a string and returns the number of vowels in the string.
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
}
print(fibfib(1)) // 0
print(fibfib(5)) // 4
print(fibfib(8)) // 24
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var fib1 = 0
var fib2 = 0
var fib3 = 1
for _ in 1...n - 2 {
fib1 = fib2
fib2 = fib3
fib3 = fib1 + fib2
}
return fib3
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var fib1 = 0
var fib2 = 0
var fib3 = 1
for _ in 1...n - 2 {
fib1 = fib2
fib2 = fib3
fib3 = fib1 + fib2
}
return fib3
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
// 1.5
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 1.6
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Example:
// Input: "A man, a plan, a canal: Panama"
// Output: true
// Input: "race a car"
// Output: false
func isPalindrome(s: String) -> Bool {
var s = s.trimmingCharacters(in: .whitespace)
s = s.replacingOccurrences(with: " ")
s = s.replacingOccurrences(with: ",")
s = s.replacingOccurrences(with: ":")
s = s.replacingOccurrences(with: ";")
s = s.replacingOccurrences(with: ".")
s = s.replacingOccurrences(with: "!")
s = s.replacingOccurrences(with: "?")
s = s.replacingOccurrences(with: "'")
s = s.replacingOccurrences(with: "/")
s = s.replacingOccurrences(with: "\\")
s = s.replacingOccurrences(with: "(")
s = s.replacingOccurrences(with: ")")
s = s.replacingOccurrences(with: "[")
s = s.replacingOccurrences(with: "]")
s = s.replacingOccurrences(with: "{")
s = s.replacingOccurrences(with: "}")
s = s.replacingOccurrences(with: "@")
s = s.replacingOccurrences(with: "#")
s = s.replacingOccurrences(with: "$")
s = s.replacingOccurrences(with: "%")
s = s.replacingOccurrences(with: "^")
s = s.replacingOccurrences(with: "&")
s = s.replacingOccurrences(with: "*")
s = s.replacingOccurrences(with: "+")
s = s.replacingOccurrences(with: "=")
s = s.replacingOccurrences(with: "|")
s = s.replacingOccurrences(with: "~")
s = s.replacingOccurrences(with: "`")
s = s.replacingOccurrences(with: "<")
s = s.replacingOccurrences(with: ">")
s = s.replacingOccurrences(with: "/")
s = s.replacingOccurrences(with: "-")
s = s.replacingOccurrences(with: "_")
s = s.replacingOccurrences(with: ".")
s = s.replacingOccurrences(with: ",")
s = s.replacingOccurrences(with: " ")
s = s.replacingOccurrences(with: "\n")
s = s.replacingOccurrences(with: "\t")
s = s.replacingOccurrences(with: "\r")
s = s.replacingOccurrences(with: "\f")
s = s.replacingOccurrences(with: "\v")
s = s.replacingOccurrences(with: "\
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3) // missing argument label 'n:' in call
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func length(s: String) -> Int {
return s.count
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char == char.digit {
count += 1
}
}
return count
}
func countWhitespace(s: String) -> Int {
var count = 0
for char in s {
if char == char.whitespace {
count += 1
}
}
return count
}
func countNonWhitespace(s: String) -> Int {
var count = 0
for char in s {
if char != char.whitespace {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the number of
// characters in the string.
// Example:
// length(s: "abcde") == 5
func length(s: String) -> Int {
return s.count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the number of
// uppercase letters in the string.
// Example:
// countUppercase(s: "abcde") == 0
// countUppercase(s: "ABCDE") == 5
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the number of
// lowercase letters in the string.
// Example:
// countLowercase(s: "abcde") == 5
// countLowercase(s: "ABCDE") == 0
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the number of
// digits in the string.
// Example:
// countDigits(s: "abcde") == 0
// countDigits(s: "12345") == 5
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char == char.digit {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as input and returns the number of
// whitespace characters in the string.
// Example:
// countWhitespace(s: "abcde") == 0
// countWhitespace(s: " abcde") == 1
// countWhitespace(s: "abcde ") == 1
// countWhitespace(s: " abcde ") == 2
func countWhitespace(s: String) -> Int {
var count = 0
for char in s {
if char == char.whitespace {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as input and returns the number of
// non-whitespace characters in the string.
// Example:
// countNonWhitespace(s: "abcde") == 5
// countNonWhitespace(s: " abcde") == 5
// countNonWhitespace(s: " abcde ") == 5
func countNonWhitespace(s: String) -> Int {
var count = 0
for char in s {
if char != char.whitespace {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char == char.digit { // value of type 'Character' has no member 'digit'
if char == char.whitespace { // value of type 'Character' has no member 'whitespace'
if char != char.whitespace { // value of type 'Character' has no member 'whitespace'
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func lengthOfString(s: String) -> Int {
return s.count
}
func numberOfWords(s: String) -> Int {
return s.split(separator: " ").count
}
func numberOfVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func numberOfConsonants(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
count += 1
}
return count
}
func numberOfUppercaseLetters(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
func numberOfLowercaseLetters(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of
// characters in the string.
// Example:
// lengthOfString(s: "Hello") == 5
// lengthOfString(s: "") == 0
// lengthOfString(s: "a") == 1
func lengthOfString(s: String) -> Int {
return s.count
}
// 2. Write a function that takes a string as input and returns the number of
// words in the string.
// Example:
// numberOfWords(s: "Hello world") == 2
// numberOfWords(s: "") == 0
// numberOfWords(s: "a") == 1
func numberOfWords(s: String) -> Int {
return s.split(separator: " ").count
}
// 3. Write a function that takes a string as input and returns the number of
// vowels in the string.
// Example:
// numberOfVowels(s: "Hello world") == 3
// numberOfVowels(s: "") == 0
// numberOfVowels(s: "a") == 1
func numberOfVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 4. Write a function that takes a string as input and returns the number of
// consonants in the string.
// Example:
// numberOfConsonants(s: "Hello world") == 7
// numberOfConsonants(s: "") == 0
// numberOfConsonants(s: "a") == 0
func numberOfConsonants(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
count += 1
}
return count
}
// 5. Write a function that takes a string as input and returns the number of
// uppercase letters in the string.
// Example:
// numberOfUppercaseLetters(s: "Hello world") == 2
// numberOfUppercaseLetters(s: "") == 0
// numberOfUppercaseLetters(s: "a") == 0
func numberOfUppercaseLetters(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
// 6. Write a function that takes a string as input and returns the number of
// lowercase letters in the string.
// Example:
// numberOfLowercaseLetters(s: "Hello world") == 5
// numberOfLowercaseLetters(s: "") == 0
// numberOfLowercaseLetters(s: "a") == 1
func numberOfLowercaseLetters(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
// 7. Write a function that takes a string as input and returns the number of
// digits in the string.
// Example:
// numberOfDigits(s: "
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
func vowelsCount(s: String) -> Int {
let vowels = "aeiouy"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
func removeSpaces(s: String) -> String {
return s.trimmingCharacters(in: .whitespace)
}
func removeVowels(s: String) -> String {
let vowels = "aeiouy"
var result = ""
for char in s {
if !vowels.contains(char) {
result += char
}
}
return result
}
func removeVowelsMiddle(s: String) -> String {
let vowels = "aeiouy"
var result = ""
var middle = false
for char in s {
if !vowels.contains(char) {
result += char
middle = true
} else if (middle) {
result += char
}
}
return result
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
let vowels = "aeiouy"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.1.2
// Write a function that takes a string as input and returns the string
// with all the spaces removed.
// Example:
// removeSpaces(s: "Hello, world!") == "Hello,world!"
func removeSpaces(s: String) -> String {
return s.trimmingCharacters(in: .whitespace)
}
// -----------------------------------------------------------------------------
// 1.1.3
// Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
func removeVowels(s: String) -> String {
let vowels = "aeiouy"
var result = ""
for char in s {
if !vowels.contains(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.4
// Write a function that takes a string as input and returns the string
// with all the vowels removed, but with the vowels in the middle of the
// string intact.
// Example:
// removeVowelsMiddle(s: "Hello, world!") == "Hll, wrld!"
func removeVowelsMiddle(s: String) -> String {
let vowels = "aeiouy"
var result = ""
var middle = false
for char in s {
if !vowels.contains(char) {
result += char
middle = true
} else if (middle) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.5
// Write a function that takes a string as input and returns the string
// with all the vowels removed, but with the vowels in the middle of the
// string intact.
// Example:
// removeVowelsMiddle(s: "Hello, world!") == "Hll, wrld!"
func removeVowelsMiddle(s: String) -> String {
let vowels = "aeiouy"
var result = ""
var middle = false
for char in s {
if !vowels.contains(char) {
result += char
middle = true
} else if (middle) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.6
// Write a function that takes a string as input and returns the string
// with all the vowels removed, but with the vowels in the middle of the
// string intact.
// Example:
// removeVowelsMiddle(s: "Hello, world!") == "Hll, wrld!"
func removeVowelsMiddle(s: String) -> String {
let vowels = "aeiouy"
var result = ""
var middle = false
for char in s {
if !vowels.contains(char) {
result += char
middle = true
} else if (middle) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.7
// Write a function that takes a string as input and returns the string
// with all the vowels removed, but with the vowels in the middle of the
// string
return s.trimmingCharacters(in: .whitespace) // type 'CharacterSet' has no member 'whitespace'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s:
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
}
}
return vowels
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ------------------
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string representing a word and returns
// the number of vowels in the string. Vowels in this case are 'a', 'e',
// 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the
// end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string representing a word and returns
// the number of vowels in the string. Vowels in this case are 'a', 'e',
// 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the
// end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string representing a word and returns
// the number of vowels in the string. Vowels in this case are 'a', 'e',
// 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the
// end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string representing a word and returns
// the number of vowels in the string. Vowels in this case are 'a', 'e',
// 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the
// end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count +=
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == "y" {
count += 1
}
default:
continue
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == "y" {
count += 1
}
default:
continue
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).split(separator: "").map(String.init)
let shiftCount = shift % digits.count
let shifted = digits.dropLast(shiftCount).concat(digits.prefix(shiftCount))
return String(shifted)
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result = [i, j]
break
}
}
}
return result
}
func countElements(nums: [Int]) -> Int {
var result = 0
var min = nums[0]
var max = nums[0]
for num in nums {
if num < min {
min = num
}
if num > max {
max = num
}
}
for num in nums {
if num > min && num < max {
result += 1
}
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).split(separator: "").map(String.init)
let shiftCount = shift % digits.count
let shifted = digits.dropLast(shiftCount).concat(digits.prefix(shiftCount))
return String(shifted)
}
// 12.10.2022
// 1. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 12.10.2022
// 1. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// twoSum(nums: [2,7,11,15], target: 9) == [0,1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result = [i, j]
break
}
}
}
return result
}
// 12.10.2022
// 1. Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
func countElements(nums: [Int]) -> Int {
var result = 0
var min = nums[0]
var max = nums[0]
for num in nums {
if num < min {
min = num
}
if num > max {
max = num
}
}
for num in nums {
if num > min && num < max {
result += 1
}
}
return result
}
// 12.10.2022
// 1. Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
func countElements(nums: [Int]) -> Int {
var result = 0
var min = nums[0]
var max = nums[0]
for num in nums {
if num < min {
min = num
}
if num > max {
max = num
}
}
for num in nums {
if num > min && num < max {
result += 1
}
}
return result
}
// 12.10.2022
// 1. Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
func countElements(nums: [Int]) -> Int {
var result = 0
var min = nums[0]
var max = nums[0]
for num in nums {
if num < min {
min = num
}
if num > max {
max = num
}
}
for num in nums {
if num > min && num < max {
result += 1
}
}
return result
}
// 12.10.2022
// 1. Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
// countElements(nums: [11,7,2,15]) == 2
func countElements(nums: [Int]) -> Int {
var result = 0
var min = nums[0]
let shifted = digits.dropLast(shiftCount).concat(digits.prefix(shiftCount)) // reference to member 'concat' cannot be resolved without a contextual type
func circularShift(x: Int, shift: Int) -> String {
let s = String(x)
let n = s.count
if shift >= n {
return s.reversed().join()
}
let i = n - shift
return s.substring(from: i) + s.substring(0, i)
}
func longestPalindrome(s: String) -> String {
var max = ""
for i in 0..<s.count {
for j in i..<s.count {
let sub = s.substring(from: i, length: j - i + 1)
if sub.isPalindrome() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let s = String(x)
let n = s.count
if shift >= n {
return s.reversed().join()
}
let i = n - shift
return s.substring(from: i) + s.substring(0, i)
}
// 2.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in 0..<s.count {
for j in i..<s.count {
let sub = s.substring(from: i, length: j - i + 1)
if sub.isPalindrome() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 3.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in 0..<s.count {
for j in i..<s.count {
let sub = s.substring(from: i, length: j - i + 1)
if sub.isPalindrome() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 4.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in 0..<s.count {
for j in i..<s.count {
let sub = s.substring(from: i, length: j - i + 1)
if sub.isPalindrome() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 5.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in 0..<s.count {
for j in i..<s.count {
let sub = s.substring(from: i, length: j - i + 1)
if sub.isPalindrome() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 6.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example 1:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(
return s.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return s.substring(from: i) + s.substring(0, i) // no exact matches in call to instance method 'substring'
return s.substring(from: i) + s.substring(0, i) // cannot convert value of type 'Int' to expected argument type 'String.Index'
let sub = s.substring(from: i, length: j - i + 1) // extra argument 'length' in call
let sub = s.substring(from: i, length: j - i + 1) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func circularShift(x: Int, shift: Int) -> String {
let str = String(x)
let len = str.count
let shiftLen = shift % len
let result = str.suffix(len - shiftLen) + str.prefix(shiftLen)
return result
}
func repeatString(str: String, n: Int) -> String {
var result = ""
for i in 0..<n {
result += str
}
return result
}
func toUpperCase(str: String) -> String {
return str.uppercaseString
}
func toLowerCase(str: String) -> String {
return str.lowercaseString
}
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
func removeConsonants(str: String) -> String {
var result = ""
for char in str {
if isConsonant(char) {
result += char
}
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let str = String(x)
let len = str.count
let shiftLen = shift % len
let result = str.suffix(len - shiftLen) + str.prefix(shiftLen)
return result
}
// 2. Given a string, return the string concatenated with itself n times where n is the length of the string.
// repeatString("Hello", 3) == "HelloHelloHello"
func repeatString(str: String, n: Int) -> String {
var result = ""
for i in 0..<n {
result += str
}
return result
}
// 3. Given a string, return the string with all the letters converted to uppercase.
// toUpperCase("Hello") == "HELLO"
func toUpperCase(str: String) -> String {
return str.uppercaseString
}
// 4. Given a string, return the string with all the letters converted to lowercase.
// toLowerCase("Hello") == "hello"
func toLowerCase(str: String) -> String {
return str.lowercaseString
}
// 5. Given a string, return the string with all the vowels removed.
// removeVowels("Hello") == "Hll"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// 6. Given a string, return the string with all the consonants removed.
// removeConsonants("Hello") == "Hll"
func removeConsonants(str: String) -> String {
var result = ""
for char in str {
if isConsonant(char) {
result += char
}
}
return result
}
// 7. Given a string, return the string with all the vowels removed.
// removeVowels("Hello") == "Hll"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// 8. Given a string, return the string with all the consonants removed.
// removeConsonants("Hello") == "Hll"
func removeConsonants(str: String) -> String {
var result = ""
for char in str {
if isConsonant(char) {
result += char
}
}
return result
}
// 9. Given a string, return the string with all the vowels removed.
// removeVowels("Hello") == "Hll"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// 10. Given a string, return the string with all the consonants removed.
// removeConsonants("Hello") == "Hll"
func removeConsonants(str: String) -> String {
var result = ""
for char in str {
if isConsonant(char) {
result += char
}
}
return result
}
// 11. Given a string, return the string with all the vowels removed.
// removeVowels("Hello") == "Hll"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if !isVowel(char) {
result += char
}
}
return result
}
// 12. Given a string, return the string with all the consonants removed.
// removeConsonants("Hello") == "Hll"
func removeConsonants(str: String) -> String {
var result = ""
for char in str {
if isConsonant(char) {
result += char
}
}
return result
}
//
return result // cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'
for i in 0..<n { // immutable value 'i' was never used; consider replacing with '_' or removing it
return str.uppercaseString // value of type 'String' has no member 'uppercaseString'
return str.lowercaseString // value of type 'String' has no member 'lowercaseString'
if !isVowel(char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if isConsonant(char) { // cannot find 'isConsonant' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x)
let length = digits.lengthOfLastSubstring()
let shiftAmount = shift % length
let shifted = String(digits.prefix(length - shiftAmount)) + String(digits.suffix(shiftAmount))
return shifted
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x)
let length = digits.lengthOfLastSubstring()
let shiftAmount = shift % length
let shifted = String(digits.prefix(length - shiftAmount)) + String(digits.suffix(shiftAmount))
return shifted
}
// 2.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
// 1.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
// 1.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
// 1.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1
let length = digits.lengthOfLastSubstring() // value of type 'String' has no member 'lengthOfLastSubstring'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map(String.init)
let n = digits.count
let shiftMod = shift % n
let result = digits.dropFirst(n - shiftMod) + digits.dropFirst(shiftMod)
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map(String.init)
let n = digits.count
let shiftMod = shift % n
let result = digits.dropFirst(n - shiftMod) + digits.dropFirst(shiftMod)
return result
}
// 2.
// Given a string, return the string reversed.
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 4.
// Given a string, return the string with all the odd characters removed.
// removeOddChars("hello") == "hllo"
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
// 5.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 6.
// Given a string, return the string with all the odd characters removed.
// removeOddChars("hello") == "hllo"
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
// 7.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 8.
// Given a string, return the string with all the odd characters removed.
// removeOddChars("hello") == "hllo"
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
// 9.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 10.
// Given a string, return the string with all the odd characters removed.
// removeOddChars("hello") == "hllo"
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
// 11.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 12.
// Given a string, return the string with all the odd characters removed.
// removeOddChars("hello") == "hllo"
func removeOddChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? $0 : "" })
}
// 13.
// Given a string, return the string with all the even characters removed.
// removeEvenChars("hello") == "hlo"
func removeEvenChars(s: String) -> String {
return String(s.map { $0.isAsciiLetter ? "" : $0 })
}
// 14.
// Given a
return result // cannot convert return expression of type 'Array<String>.SubSequence' (aka 'ArraySlice<String>') to return type 'String'
return String(s.map { $0.isAsciiLetter ? "" : $0 }) // result values in '? :' expression have mismatching types 'String' and 'String.Element' (aka 'Character')
return String(s.map { $0.isAsciiLetter ? "" : $0 }) // value of type 'String.Element' (aka 'Character') has no member 'isAsciiLetter'
return String(s.map { $0.isAsciiLetter ? $0 : "" }) // value of type 'String.Element' (aka 'Character') has no member 'isAsciiLetter'
return String(s.map { $0.isAsciiLetter ? $0 : "" }) // no exact matches in call to initializer
return String(s.map { $0.isAsciiLetter ? $0 : "" }) // result values in '? :' expression have mismatching types 'String.Element' (aka 'Character') and 'String'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map(Character.init)
let shiftCount = digits.count
let shiftMod = shift % shiftCount
let shiftedDigits = digits.dropFirst(shiftCount - shiftMod)
let shiftedString = String(shiftedDigits)
return shiftedString
}
func firstTwo(s: String) -> String {
if s.count < 2 {
return s
}
return s.prefix(2)
}
func stringTimes(s: String, n: Int) -> String {
var result = ""
for _ in 0..<n {
result += s
}
return result
}
func frontTimes(s: String, n: Int) -> String {
let front = s.prefix(min(3, s.count))
var result = ""
for _ in 0..<n {
result += front
}
return result
}
func equalIsNot(s: String) -> Bool {
let isCount = s.count(for: "is")
let notCount = s.count(for: "not")
return isCount == notCount
}
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
func stringSplosion(s: String) -> String {
var result = ""
for i in 0..<s.count {
result += s[0..<i+1]
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map(Character.init)
let shiftCount = digits.count
let shiftMod = shift % shiftCount
let shiftedDigits = digits.dropFirst(shiftCount - shiftMod)
let shiftedString = String(shiftedDigits)
return shiftedString
}
// 2.
// Given a string s, return the string made of its first two chars, so if the
// string length is less than 2, return whatever there is, so "X" and "" both
// return "X".
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
func firstTwo(s: String) -> String {
if s.count < 2 {
return s
}
return s.prefix(2)
}
// 3.
// Given a string and a non-negative int n, return a larger string that is n
// copies of the original string.
// stringTimes("Hi", 2) == "HiHi"
// stringTimes("Hi", 3) == "HiHiHi"
// stringTimes("Hi", 1) == "Hi"
func stringTimes(s: String, n: Int) -> String {
var result = ""
for _ in 0..<n {
result += s
}
return result
}
// 4.
// Given a string and a non-negative int n, we'll say that the front of the
// string is the first 3 chars, or whatever is there if the string is less than
// length 3. Return n copies of the front;
// frontTimes("Chocolate", 2) == "ChoCho"
// frontTimes("Chocolate", 3) == "ChoChoCho"
// frontTimes("Abc", 3) == "AbcAbcAbc"
func frontTimes(s: String, n: Int) -> String {
let front = s.prefix(min(3, s.count))
var result = ""
for _ in 0..<n {
result += front
}
return result
}
// 5.
// Given a string, return true if the number of appearances of "is" anywhere
// in the string is equal to the number of appearances of "not" anywhere in
// the string (case sensitive).
// equalIsNot("This is not") == true
// equalIsNot("This is notnot") == false
// equalIsNot("noisxxnotyynotxisi") == true
func equalIsNot(s: String) -> Bool {
let isCount = s.count(for: "is")
let notCount = s.count(for: "not")
return isCount == notCount
}
// 6.
// Given a string, return a new string made of every other char starting with
// the first, so "Hello" yields "Hlo".
// stringBits("Hello") == "Hlo"
// stringBits("Hi") == "H"
// stringBits("Heeololeo") == "Hello"
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
// 7.
// Given a non-empty string like "Code" return a string like "CCoCodCode".
// stringSplosion("Code") == "CCoCodCode"
// stringSplosion("abc") == "aababc"
// stringSplosion("ab") == "aab"
func stringSplosion(s: String) -> String {
var result = ""
for i in 0..<s.count {
result += s[0..<i+1]
}
return result
}
// 8.
// Given a string, return the count of the number of times that a substring
// length 2 appears in the string and also as the last 2 chars of the string,
// so "hixxxhi" yields 1 (we won't count the end
return s.prefix(2) // no 'prefix' candidates produce the expected contextual result type 'String'
let isCount = s.count(for: "is") // cannot call value of non-function type 'Int'
let notCount = s.count(for: "not") // cannot call value of non-function type 'Int'
result += s[i] // no exact matches in call to subscript
result += s[0..<i+1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int($0) }
let shiftCount = shift % digits.count
let shifted = digits.dropFirst(digits.count - shiftCount)
let shifted2 = shifted.dropLast(shiftCount)
return String(shifted2).joined(separator: "")
}
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
for i in 0..<sorted.count - 2 {
if sorted[i] + sorted[i + 1] > sorted[i + 2] {
return sorted[i] + sorted[i + 1] + sorted[i + 2]
}
}
return 0
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int($0) }
let shiftCount = shift % digits.count
let shifted = digits.dropFirst(digits.count - shiftCount)
let shifted2 = shifted.dropLast(shiftCount)
return String(shifted2).joined(separator: "")
}
// 2.
// Given an integer array nums, return the largest perimeter of a triangle with a non-zero area,
// formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
// largestPerimeter([2, 1, 2]) == 5
// largestPerimeter([1, 2, 1]) == 0
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
for i in 0..<sorted.count - 2 {
if sorted[i] + sorted[i + 1] > sorted[i + 2] {
return sorted[i] + sorted[i + 1] + sorted[i + 2]
}
}
return 0
}
// 3.
// Given an integer array nums, return the largest perimeter of a triangle with a non-zero area,
// formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
// largestPerimeter([2, 1, 2]) == 5
// largestPerimeter([1, 2, 1]) == 0
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
for i in 0..<sorted.count - 2 {
if sorted[i] + sorted[i + 1] > sorted[i + 2] {
return sorted[i] + sorted[i + 1] + sorted[i + 2]
}
}
return 0
}
// 4.
// Given an integer array nums, return the largest perimeter of a triangle with a non-zero area,
// formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
// largestPerimeter([2, 1, 2]) == 5
// largestPerimeter([1, 2, 1]) == 0
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
for i in 0..<sorted.count - 2 {
if sorted[i] + sorted[i + 1] > sorted[i + 2] {
return sorted[i] + sorted[i + 1] + sorted[i + 2]
}
}
return 0
}
// 5.
// Given an integer array nums, return the largest perimeter of a triangle with a non-zero area,
// formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
// largestPerimeter([2, 1, 2]) == 5
// largestPerimeter([1, 2, 1]) == 0
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
for i in 0..<sorted.count - 2 {
if sorted[i] + sorted[i + 1] > sorted[i + 2] {
return sorted[i] + sorted[i + 1] + sorted[i + 2]
}
}
return 0
}
// 6.
// Given an integer array nums, return the largest perimeter of a triangle with a non-zero area,
// formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
// largestPerimeter([2, 1, 2]) == 5
// largestPerimeter([1, 2, 1]) == 0
func largestPerimeter(nums: [Int]) -> Int {
let sorted = nums.sorted(by: { $0 < $1 })
let digits = String(x).map { Int($0) } // no exact matches in call to initializer
let digits = String(x).map { Int($0) } // no exact matches in call to initializer
return String(shifted2).joined(separator: "") // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).count
let shift = shift % digits
return String(x).prefix(digits - shift) + String(x).suffix(shift)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).count
let shift = shift % digits
return String(x).prefix(digits - shift) + String(x).suffix(shift)
}
// 2022-09-21-14-51-41
// 2022-09-21-14-52-10
// 2022-09-21-14-52-53
// 2022-09-21-14-53-11
// 2022-09-21-14-53-42
// 2022-09-21-14-54-22
// 2022-09-21-14-54-43
// 2022-09-21-14-55-11
// 2022-09-21-14-55-30
// 2022-09-21-14-55-43
// 2022-09-21-14-56-00
// 2022-09-21-14-56-11
// 2022-09-21-14-56-22
// 2022-09-21-14-56-30
// 2022-09-21-14-56-43
// 2022-09-21-14-57-00
// 2022-09-21-14-57-11
// 2022-09-21-14-57-22
// 2022-09-21-14-57-30
// 2022-09-21-14-57-43
// 2022-09-21-14-58-00
// 2022-09-21-14-58-11
// 2022-09-21-14-58-22
// 2022-09-21-14-58-30
// 2022-09-21-14-58-43
// 2022-09-21-14-59-00
// 2022-09-21-14-59-11
// 2022-09-21-14-59-22
// 2022-09-21-14-59-30
// 2022-09-21-14-59-43
// 2022-09-21-14-60-00
// 2022-09-21-14-60-11
// 2022-09-21-14-60-22
// 2022-09-21-14-60-30
// 2022-09-21-14-60-43
// 2022-09-21-14-61-00
// 2022-09-21-14-61-11
// 2022-09-21-14-61-22
// 2022-09-21-14-61-30
// 2022-09-21-14-61-43
// 2022-09-21-14-62-00
// 2022-09-21-14-62-11
// 2022-09-21-14-62-22
// 2022-09-21-14-62-30
// 2022-
return String(x).prefix(digits - shift) + String(x).suffix(shift) // cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).split(separator: "").map { Int($0) }
let shiftCount = shift % digits.count
let shiftedDigits = digits.dropLast(shiftCount)
let reversedShiftedDigits = shiftedDigits.reversed()
return String(reversedShiftedDigits.joined(separator: ""))
}
func firstTwo(str: String) -> String {
return str.prefix(min: 2)
}
func isNot(str: String) -> Bool {
let isCount = str.count(for: "is")
let notCount = str.count(for: "not")
return isCount == notCount
}
func frontBack(str: String) -> String {
return str.last() + str.subString(1, length: str.count - 2) + str.first()
}
func front3(str: String) -> String {
return str.prefix(3) + str.prefix(3) + str.prefix(3)
}
func front23(str: String) -> String {
return str.prefix(2) + str.suffix(2)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).split(separator: "").map { Int($0) }
let shiftCount = shift % digits.count
let shiftedDigits = digits.dropLast(shiftCount)
let reversedShiftedDigits = shiftedDigits.reversed()
return String(reversedShiftedDigits.joined(separator: ""))
}
// -----------------------------------------------------------------------------
// 2.
// Given a string, return the string made of its first two chars, so the String
// "Hello" yields "He". If the string is shorter than length 2, return whatever
// there is, so "X" yields "X", and the empty string "" yields the empty string
// "".
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(str: String) -> String {
return str.prefix(min: 2)
}
// -----------------------------------------------------------------------------
// 3.
// Given a string, return true if the number of appearances of "is" anywhere in
// the string is equal to the number of appearances of "not" anywhere in the
// string (case sensitive).
// isNot("not not is not") == true
// isNot("is is not not") == false
// isNot("is is not is") == false
func isNot(str: String) -> Bool {
let isCount = str.count(for: "is")
let notCount = str.count(for: "not")
return isCount == notCount
}
// -----------------------------------------------------------------------------
// 4.
// Given a string, return a new string where the first and last chars have been
// exchanged.
// frontBack("code") == "eodc"
// frontBack("a") == "a"
// frontBack("ab") == "ba"
func frontBack(str: String) -> String {
return str.last() + str.subString(1, length: str.count - 2) + str.first()
}
// -----------------------------------------------------------------------------
// 5.
// Given a string, return a new string where the first and last chars have been
// exchanged.
// front3("Java") == "JavJavJav"
// front3("Chocolate") == "ChoChoCho"
// front3("abc") == "abcabcabc"
func front3(str: String) -> String {
return str.prefix(3) + str.prefix(3) + str.prefix(3)
}
// -----------------------------------------------------------------------------
// 6.
// Given a string, return a new string where the first and last chars have been
// exchanged.
// front23("Java") == "avJav"
// front23("Chocolate") == "ChoCho"
// front23("abc") == "abcabc"
func front23(str: String) -> String {
return str.prefix(2) + str.suffix(2)
}
// -----------------------------------------------------------------------------
// 7.
// Given a string, return true if the number of appearances of "is" anywhere in
// the string is equal to the number of appearances of "not" anywhere in the
// string (case sensitive).
// mixStart("mix snacks") == true
// mixStart("pix snacks") == true
// mixStart("piz snacks") == false
// mixStart("pxiq snacks") == true
// mixStart("piq snacks") == false
// mixStart("pizx snacks") == false
// mixStart
return String(reversedShiftedDigits.joined(separator: "")) // no exact matches in call to instance method 'joined'
return str.prefix(min: 2) // no exact matches in call to instance method 'prefix'
return str.prefix(min: 2) // no 'prefix' candidates produce the expected contextual result type 'String'
let isCount = str.count(for: "is") // cannot call value of non-function type 'Int'
let notCount = str.count(for: "not") // cannot call value of non-function type 'Int'
return str.last() + str.subString(1, length: str.count - 2) + str.first() // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
return str.last() + str.subString(1, length: str.count - 2) + str.first() // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
return str.last() + str.subString(1, length: str.count - 2) + str.first() // value of type 'String' has no member 'subString'
return str.prefix(3) + str.prefix(3) + str.prefix(3) // cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'
return str.prefix(2) + str.suffix(2) // cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters
let length = digits.count
let shiftMod = shift % length
let newDigits = digits.dropFirst(shiftMod)
let newDigits2 = newDigits.dropLast(length - shiftMod)
return String(newDigits2)
}
func firstTwo(s: String) -> String {
return s.prefix(min(2, s.count))
}
func withoutEnd(s: String) -> String {
return s[1..<s.count - 1]
}
func middleTwo(s: String) -> String {
return s[s.count / 2 - 1..<s.count / 2 + 1]
}
func endsLy(s: String) -> Bool {
return s.hasSuffix("ly")
}
func nTwice(s: String, n: Int) -> String {
return s.prefix(n) + s.suffix(n)
}
func twoChar(s: String, index: Int) -> String {
return s.prefix(min(2, s.count))
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).characters
let length = digits.count
let shiftMod = shift % length
let newDigits = digits.dropFirst(shiftMod)
let newDigits2 = newDigits.dropLast(length - shiftMod)
return String(newDigits2)
}
// 2.
// Given a string, return the string made of its first two chars, so the String
// "Hello" yields "He". If the string is shorter than length 2, return whatever
// there is, so "X" yields "X", and the empty string "" yields the empty string
// "".
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(s: String) -> String {
return s.prefix(min(2, s.count))
}
// 3.
// Given a string, return a version without the first and last char, so
// "Hello" yields "ell". The string length will be at least 2.
// withoutEnd("Hello") == "ell"
// withoutEnd("java") == "av"
// withoutEnd("coding") == "odin"
func withoutEnd(s: String) -> String {
return s[1..<s.count - 1]
}
// 4.
// Given a string, return a string length 2 made of its first 2 chars. If the
// string length is less than 2, use '@' for the missing chars.
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(s: String) -> String {
return s.prefix(min(2, s.count))
}
// 5.
// Given a string of even length, return a string made of the middle two chars,
// so the string "string" yields "ri". The string length will be at least 2.
// middleTwo("string") == "ri"
// middleTwo("code") == "od"
// middleTwo("Practice") == "ct"
func middleTwo(s: String) -> String {
return s[s.count / 2 - 1..<s.count / 2 + 1]
}
// 6.
// Given a string, return true if it ends in "ly".
// endsLy("oddly") == true
// endsLy("y") == false
// endsLy("oddy") == false
func endsLy(s: String) -> Bool {
return s.hasSuffix("ly")
}
// 7.
// Given a string and an int n, return a string made of the first and last n
// chars from the string. The string length will be at least n.
// nTwice("Hello", 2) == "Helo"
// nTwice("Chocolate", 3) == "Choate"
// nTwice("Chocolate", 1) == "Ce"
func nTwice(s: String, n: Int) -> String {
return s.prefix(n) + s.suffix(n)
}
// 8.
// Given a string and an index, return a string length 2 starting at the index
// given, or if the index is too big or too small to define a string length
// 2, use the first 2 chars. The original string will be length 2 or more
// and the index will be at least 0.
// twoChar("java", 0) == "ja"
// twoChar("java", 2) == "va"
// twoChar("java", 3) == "ja"
// twoChar("java", 100) == "ja"
func twoChar(s: String, index: Int) -> String {
return s.prefix(min(2, s.count))
}
// 9.
// Given a string and a non-negative int n, return a larger string that is n
// copies of the original string.
// stringTimes("Hi
let digits = String(x).characters // 'characters' is unavailable: Please use String directly
return s.prefix(min(2, s.count)) // no 'prefix' candidates produce the expected contextual result type 'String'
return s[1..<s.count - 1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return s[s.count / 2 - 1..<s.count / 2 + 1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return s.prefix(n) + s.suffix(n) // no '+' candidates produce the expected contextual result type 'String'
return s.prefix(min(2, s.count)) // no 'prefix' candidates produce the expected contextual result type 'String'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if char.isUpper { // value of type 'Character' has no member 'isUpper'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the sum of the lower characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 65
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 101
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the sum of the digits only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the sum of the lower characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 65
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 101
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
if char.isUpper { // value of type 'Character' has no member 'isUpper'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int { // invalid redeclaration of 'digitSum(s:)'
if char.isLower { // value of type 'Character' has no member 'isLower'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int { // invalid redeclaration of 'digitSum(s:)'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// Task
// Write a function that takes a string as input
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Examples:
// "Example Input" ==> "iNPUT eXAMPLE"
// "Warmup - Strings" ==> "gnimmAReW - dnaS"
// "This is a test" ==> "tSET a si htiw"
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, return a new string with the reversed order of characters.
// Examples:
// "example" ==> "elpmaxe"
// "coding" ==> "gniidoC"
// "12345" ==> "54321"
// "Sadie" ==> "ediyS"
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Examples:
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
// " " is a valid palindrome.
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Examples:
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
// " " is a valid palindrome.
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Examples:
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
// " " is a valid palindrome.
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Examples:
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
// " " is a valid palindrome.
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Examples:
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Task
// Given a string, find the first character that is not repeated anywhere in the string.
// Examples:
// firstNotRepeatedCharacter(s: "abcdcaf") == "b"
// firstNotRepeatedCharacter(s: "abcd") == "e"
// firstNotRepeatedCharacter(s: "") == ""
// firstNotRepeatedCharacter(s: "aabbcc") == "e"
// firstNotRepeatedCharacter(s: "aabbccddeef") == "f"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyz") == "a"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba") == "a"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba") == "b"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba") == "c"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba") == "d"
// firstNotRepeatedCharacter(s: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcbaabcdef
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// 2. Write a function that takes a string as input and returns the sum of the lower characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 98
// digitSum(s: "abcCd") == 100
// digitSum(s: "helloE") == 101
// digitSum(s: "woArBld") == 101
// digitSum(s: "aAaaaXa") == 101
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
// 3. Write a function that takes a string as input and returns the sum of the digits only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 1
// digitSum(s: "abcCd") == 10
// digitSum(s: "helloE") == 11
// digitSum(s: "woArBld") == 11
// digitSum(s: "aAaaaXa") == 11
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += char.asciiValue
}
}
return sum
}
// 4. Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// 5. Write a function that takes a string as input and returns the sum of the lower characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 98
// digitSum(s: "abcCd") == 100
// digitSum(s: "helloE") == 101
// digitSum(s: "woArBld") == 101
// digitSum(s: "aAaaaXa") == 101
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isLower {
sum += char.asciiValue
}
}
return sum
}
// 6. Write a function that takes a string as input and returns the sum of the digits only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 1
// digitSum(s: "abcCd") == 10
// digitSum(s: "helloE") == 11
// digitSum(s: "woArBld") == 11
// digitSum(s: "aAaaaXa") == 11
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += char.asciiValue
}
}
return sum
}
// 7. Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
//
if char.isUpper { // value of type 'Character' has no member 'isUpper'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int { // invalid redeclaration of 'digitSum(s:)'
if char.isLower { // value of type 'Character' has no member 'isLower'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int { // invalid redeclaration of 'digitSum(s:)'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpperCased {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUpper {
sum += char.asciiValue
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------
if char.isUpper { // value of type 'Character' has no member 'isUpper'
sum += char.asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 2:
// Given a string that represents a number of apples and oranges ,
// return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 3:
// Given a string that represents a number of apples and oranges ,
// return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 4:
// Given a string that represents a number of apples and oranges ,
// return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 5:
// Given a string that represents a number of apples and oranges ,
// return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
let mango = n - apples - oranges
return mango
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let splitted = s.split(separator: " ")
let apples = Int(splitted[0])!
let oranges = Int(splitted[2])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let splitted = s.split(separator: " ")
let apples = Int(splitted[0])!
let oranges = Int(splitted[2])!
let mango = n - apples - oranges
return mango
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(String(s.split(" apples")[0]))
let oranges = Int(String(s.split(" oranges")[0]))
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(String(s.split(" apples")[0]))
let oranges = Int(String(s.split(" oranges")[0]))
return n - apples - oranges
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let apples = Int(String(s.split(" apples")[0])) // missing argument label 'separator:' in call
let oranges = Int(String(s.split(" oranges")[0])) // missing argument label 'separator:' in call
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let split = s.split(separator: " ")
let apples = Int(split[0])!
let oranges = Int(split[2])!
let mango = n - apples - oranges
return mango
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let splitted = s.split(separator: " ")
let apples = Int(splitted[0])!
let oranges = Int(splitted[2])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let splitted = s.split(separator: " ")
let apples = Int(splitted[0])!
let oranges = Int(splitted[2])!
let mango = n - apples - oranges
return mango
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
let mango = n - apples - oranges
return mango
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples")[0])!
let oranges = Int(s.split(separator: " oranges")[0])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples")[0])!
let oranges = Int(s.split(separator: " oranges")[0])!
return n - apples - oranges
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
return n - apples - oranges
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
let mango = n - apples - oranges
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.split(separator: " apples and ")[0])!
let oranges = Int(s.split(separator: " oranges and ")[0])!
let mango = n - apples - oranges
return mango
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
struct pluck_test {
static let input = [4, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [1, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [] as [Int]
static let expected = [] as [Int]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [5, 0, 3, 0, 4, 2]
static let expected = [0, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
}
struct pluck_test {
static let input = [4, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [1, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [] as [Int]
static let expected = [] as [Int]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [5, 0, 3, 0, 4, 2]
static let expected = [0, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
static let expected = [2, 1]
static func test() {
let actual = pluck(input)
assert(actual == expected)
}
}
struct pluck_test {
static let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
let actual = pluck(input) // missing argument label 'arr:' in call
struct pluck_test { // invalid redeclaration of 'pluck_test'
let actual = pluck(input) // missing argument label 'arr:' in call
struct pluck_test { // invalid redeclaration of 'pluck_test'
let actual = pluck(input) // missing argument label 'arr:' in call
struct pluck_test { // invalid redeclaration of 'pluck_test'
let actual = pluck(input) // missing argument label 'arr:' in call
struct pluck_test { // invalid redeclaration of 'pluck_test'
let actual = pluck(input) // missing argument label 'arr:' in call
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
let minEven = arr.min(by: { $0 % 2 == 0 })
let index = arr.firstIndex(of: minEven!)
return [minEven!, index!]
}
struct pluck_test {
static let input = [4, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test2 {
static let input = [1, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test3 {
static let input = []
static let expected = []
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test4 {
static let input = [5, 0, 3, 0, 4, 2]
static let expected = [0, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
let minEven = arr.min(by: { $0 % 2 == 0 })
let index = arr.firstIndex(of: minEven!)
return [minEven!, index!]
}
struct pluck_test {
static let input = [4, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test2 {
static let input = [1, 2, 3]
static let expected = [2, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test3 {
static let input = []
static let expected = []
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test4 {
static let input = [5, 0, 3, 0, 4, 2]
static let expected = [0, 1]
static func test() {
let actual = pluck(arr: input)
print("pluck(arr: \(input)) == \(actual)")
print("expected: \(expected)")
print("actual: \(actual)")
print("")
}
}
struct pluck_test5 {
static let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 12
let minEven = arr.min(by: { $0 % 2 == 0 }) // contextual closure type '(Int, Int) throws -> Bool' expects 2 arguments, but 1 was used in closure body
static let input = [] // empty collection literal requires an explicit type
static let expected = [] // empty collection literal requires an explicit type
let actual = pluck(arr: input) // cannot convert value of type '[Any]' to expected argument type '[Int]'
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (i, v) in arr.enumerated() {
if v % 2 == 0 && v < min {
min = v
index = i
}
}
return [min, index]
}
}
// -----------------------------------------------------------------------------
struct Pluck {
static func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
var min = Int.max
var index = 0
for (
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
// }}}
// {{{
// Task:
// Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
// }}}
// {{{
// Task:
// Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEven = Int.max
var smallestIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEven {
smallestEven = arr[i]
smallestIndex = i
}
}
return [smallestEven, smallestIndex]
}
// }}}
// {{{
// Task:
// Given an array representing a branch
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
// }}}
// {{{
// https://www.codewars.com/kata/563b40bd609f623a300005b7/train/swift
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
// 5 kyu
//
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
let minEven = Int.min
let minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.isEmpty {
return []
}
let minEven = Int.min
let minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
minEven = arr[i] // cannot assign to value: 'minEven' is a 'let' constant
minEvenIndex = i // cannot assign to value: 'minEvenIndex' is a 'let' constant
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = 10000
var smallestEvenIndex = 0
var smallestEvenNode = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEvenValue {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenNode = arr[i]
}
}
return [smallestEvenNode, smallestEvenIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = 10000
var smallestEvenIndex = 0
var smallestEvenNode = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < smallestEvenValue {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenNode = arr[i]
}
}
return [smallestEvenNode, smallestEvenIndex]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = 0
var smallestEvenIndex = 0
var smallestEvenCount = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 {
if smallestEvenValue == 0 {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenCount = 1
} else if arr[i] == smallestEvenValue {
smallestEvenCount += 1
} else if arr[i] < smallestEvenValue {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenCount = 1
}
}
}
if smallestEvenValue == 0 {
return []
} else {
return [smallestEvenValue, smallestEvenIndex]
}
}
struct pluck_test {
static let test_cases: [Any] = [
[4, 2, 3],
[1, 2, 3],
[] as [Int],
[5, 0, 3, 0, 4, 2],
]
static func run() {
for test_case in test_cases {
print("pluck(\(test_case)) == \(pluck(test_case))")
}
}
}
import Cocoa
public class Solution {
public static var result: Bool = false
public static func hasPathSum(root: TreeNode?, sum: Int) -> Bool {
if root == nil {
return false
}
if root.left == nil && root.right == nil {
return root.val == sum
}
if root.left != nil {
hasPathSum(root.left, sum - root.val)
}
if root.right != nil {
hasPathSum(root.right, sum - root.val)
}
return result
}
public static func run() {
let root = TreeNode(val: 5)
root.left = TreeNode(val: 4)
root.right = TreeNode(val: 8)
root.left.left = TreeNode(val: 11)
root.left.left.left = TreeNode(val: 7)
root.left.left.right = TreeNode(val: 2)
root.right.left = TreeNode(val: 13)
root.right.right = TreeNode(val: 4)
root.right.right.right = TreeNode(val: 1)
print(hasPathSum(root: root, sum: 22))
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var smallestEvenValue = 0
var smallestEvenIndex = 0
var smallestEvenCount = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 {
if smallestEvenValue == 0 {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenCount = 1
} else if arr[i] == smallestEvenValue {
smallestEvenCount += 1
} else if arr[i] < smallestEvenValue {
smallestEvenValue = arr[i]
smallestEvenIndex = i
smallestEvenCount = 1
}
}
}
if smallestEvenValue == 0 {
return []
} else {
return [smallestEvenValue, smallestEvenIndex]
}
}
struct pluck_test {
static let test_cases: [Any] = [
[4, 2, 3],
[1, 2, 3],
[] as [Int],
[5, 0, 3, 0, 4, 2],
]
static func run() {
for test_case in test_cases {
print("pluck(\(test_case)) == \(pluck(test_case))")
}
}
}
pluck_test.run()<|endoftext|>//
// main.swift
// 112. Path Sum
//
// Created by yuhua on 2020/12/13.
//
//https://leetcode.com/problems/path-sum/
//
//Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
//
//Note: A leaf is a node with no children.
//
//Example:
//
//Given the below binary tree and sum = 22,
//
// 5
// / \
// 4 8
// / / \
// 11 13 4
// / \ \
//7 2 1
//return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
import Cocoa
public class Solution {
public static var result: Bool = false
public static func hasPathSum(root: TreeNode?, sum: Int) -> Bool {
if root == nil {
return false
}
if root.left == nil && root.right == nil {
return root.val == sum
}
if root.left != nil {
hasPathSum(root.left, sum - root.val)
}
if root.right != nil {
hasPathSum(root.right, sum - root.val)
}
return result
}
public static func run() {
let root = TreeNode(val: 5)
root.left = TreeNode(val: 4)
root.right = TreeNode(val: 8)
root.left.left = TreeNode(val: 11)
root.left.left.left = TreeNode(val: 7)
root.left.left.right = TreeNode(val: 2)
root.right.left = TreeNode(val: 13)
root.right.right = TreeNode(val: 4)
root.right.right.right = TreeNode(val: 1)
print(hasPathSum(root: root, sum: 22))
}
}
Solution.run()<|endoftext|>//
// main.swift
// 104. Maximum Depth of Binary Tree
//
// Created by yuhua on 2020/12/13.
//
//https://leetcode.com/problems/maximum-depth-of-binary-tree/
//
//Given a binary tree, find its maximum depth.
//
//The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
//
//Note: A leaf is
print("pluck(\(test_case)) == \(pluck(test_case))") // missing argument label 'arr:' in call
print("pluck(\(test_case)) == \(pluck(test_case))") // cannot convert value of type 'Any' to expected argument type '[Int]'
public static func hasPathSum(root: TreeNode?, sum: Int) -> Bool { // cannot find type 'TreeNode' in scope
let root = TreeNode(val: 5) // cannot find 'TreeNode' in scope
root.left = TreeNode(val: 4) // cannot find 'TreeNode' in scope
root.right = TreeNode(val: 8) // cannot find 'TreeNode' in scope
root.left.left = TreeNode(val: 11) // cannot find 'TreeNode' in scope
root.left.left.left = TreeNode(val: 7) // cannot find 'TreeNode' in scope
root.left.left.right = TreeNode(val: 2) // cannot find 'TreeNode' in scope
root.right.left = TreeNode(val: 13) // cannot find 'TreeNode' in scope
root.right.right = TreeNode(val: 4) // cannot find 'TreeNode' in scope
root.right.right.right = TreeNode(val: 1) // cannot find 'TreeNode' in scope
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
struct PluckTests {
static let allTests: [XCTest] = [
PluckTests.test1,
PluckTests.test2,
PluckTests.test3,
PluckTests.test4,
]
static func test1() {
let arr = [4, 2, 3]
let expected = [2, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test2() {
let arr = [1, 2, 3]
let expected = [2, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test3() {
let arr = []
let expected = []
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test4() {
let arr = [5, 0, 3, 0, 4, 2]
let expected = [0, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
}
class PluckTestsRunner: XCTestCase {
func testAll() {
XCTestRunner.runAll(tests: PluckTests.allTests)
}
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
if arr.count == 0 {
return []
}
var minEven = Int.max
var minEvenIndex = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 && arr[i] < minEven {
minEven = arr[i]
minEvenIndex = i
}
}
return [minEven, minEvenIndex]
}
// -----------------------------------------------------------------------------
struct PluckTests {
static let allTests: [XCTest] = [
PluckTests.test1,
PluckTests.test2,
PluckTests.test3,
PluckTests.test4,
]
static func test1() {
let arr = [4, 2, 3]
let expected = [2, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test2() {
let arr = [1, 2, 3]
let expected = [2, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test3() {
let arr = []
let expected = []
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
static func test4() {
let arr = [5, 0, 3, 0, 4, 2]
let expected = [0, 1]
let actual = pluck(arr: arr)
XCTAssertEqual(expected, actual)
}
}
// -----------------------------------------------------------------------------
class PluckTestsRunner: XCTestCase {
func testAll() {
XCTestRunner.runAll(tests: PluckTests.allTests)
}
}
// -----------------------------------------------------------------------------
let runner = PluckTestsRunner()
runner.testAll()<|endoftext|>// -----------------------------------------------------------------------------
// 1. Write a function that takes an array of numbers and returns the sum of all the numbers.
// Example: sum([1, 2, 3]) == 6
// Example: sum([1, 2, 3, 4, 5]) == 15
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 120
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 180
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 240
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 300
// Example: sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
static let allTests: [XCTest] = [ // cannot find type 'XCTest' in scope
let arr = [] // empty collection literal requires an explicit type
let expected = [] // empty collection literal requires an explicit type
let actual = pluck(arr: arr) // cannot convert value of type '[Any]' to expected argument type '[Int]'
XCTAssertEqual(expected, actual) // type 'Any' cannot conform to 'Equatable'
XCTestRunner.runAll(tests: PluckTests.allTests) // cannot find 'XCTestRunner' in scope
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
count = 1
} else if i == max {
count += 1
maxCount = max(maxCount, count)
}
}
return maxCount > max ? max : -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
count = 1
} else if i == max {
count += 1
maxCount = max(maxCount, count)
}
}
return maxCount > max ? max : -1
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
maxCount = max(maxCount, count) // cannot call value of non-function type 'Int'
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
for i in dict {
if i.value > count {
max = i.key
count = i.value
}
}
return max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
for i in dict {
if i.value > count {
max = i.key
count = i.value
}
}
return max
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func search(lst: [Int]) -> Int {
var result = -1
var max = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
if dict[i] > max {
max = dict[i]
}
}
for i in dict {
if i.value >= i.key {
result = i.key
break
}
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var result = -1
var max = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
if dict[i] > max {
max = dict[i]
}
}
for i in dict {
if i.value >= i.key {
result = i.key
break
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if dict[i] > max { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
max = dict[i] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func search(lst: [Int]) -> Int {
var max = 0
var maxFreq = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
if dict[i] > maxFreq {
maxFreq = dict[i]
max = i
}
}
if maxFreq >= max {
return max
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxFreq = 0
var dict = [Int: Int]()
for i in lst {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
if dict[i] > maxFreq {
maxFreq = dict[i]
max = i
}
}
if maxFreq >= max {
return max
} else {
return -1
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if dict[i] > maxFreq { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
maxFreq = dict[i] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
var lst = lst.sorted()
for i in lst {
if i > max {
max = i
count = 1
} else if i == max {
count += 1
}
}
if count >= max {
return max
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
var lst = lst.sorted()
for i in lst {
if i > max {
max = i
count = 1
} else if i == max {
count += 1
}
}
if count >= max {
return max
} else {
return -1
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
var lst = lst.sorted() // variable 'lst' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
if i > 0 {
if i == count {
count += 1
} else {
count = 1
}
}
}
if maxCount > count {
return max
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
if i > 0 {
if i == count {
count += 1
} else {
count = 1
}
}
}
if maxCount > count {
return max
} else {
return -1
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
for i in lst {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
maxCount = count
max = i
}
}
return max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
for i in lst {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
maxCount = count
max = i
}
}
return max
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var maxFreq = 0
var count = 0
var freq = 0
for i in lst {
count = 0
freq = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
maxCount = count
max = i
}
if count == maxCount {
if i > max {
max = i
}
}
if count > maxFreq {
maxFreq = count
}
}
if maxFreq >= max {
return max
}
return -1
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var maxFreq = 0
var count = 0
var freq = 0
for i in lst {
count = 0
freq = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
maxCount = count
max = i
}
if count == maxCount {
if i > max {
max = i
}
}
if count > maxFreq {
maxFreq = count
}
}
if maxFreq >= max {
return max
}
return -1
}
print(search([4, 1, 2, 2, 3, 1]))
print(search([1, 2, 2, 3, 3, 3, 4, 4, 4]))
print(search([5, 5, 4, 4, 4]))
print(search([1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
var freq = 0 // variable 'freq' was written to, but never read
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
var maxFreq = 0
for i in lst {
if i > max {
max = i
}
if i == max {
count += 1
}
if i == maxCount {
maxFreq += 1
}
if i > maxCount {
maxCount = i
maxFreq = 1
}
}
if maxFreq > maxCount {
return max
}
return maxCount
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
var maxFreq = 0
for i in lst {
if i > max {
max = i
}
if i == max {
count += 1
}
if i == maxCount {
maxFreq += 1
}
if i > maxCount {
maxCount = i
maxFreq = 1
}
}
if maxFreq > maxCount {
return max
}
return maxCount
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
if i > 0 {
count += 1
}
}
if maxCount >= count {
return max
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var maxCount = 0
var count = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
if i > 0 {
count += 1
}
}
if maxCount >= count {
return max
} else {
return -1
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
public func strangeSortList<T: Comparable>(_ lst: [T]) -> [T] {
if lst.isEmpty {
return []
}
var result = [T]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[T]' has no member 'pop'
result.append(sorted.pop()) // value of type '[T]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
for i in 1...lst.count {
result.sort()
result.reverse()
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
for i in 1...lst.count {
result.sort()
result.reverse()
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
for i in 1...lst.count { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var result = [Int]()
var sorted = lst.sorted()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
if lst.isEmpty {
return []
}
var sorted = lst.sorted()
var result = [Int]()
while !sorted.isEmpty {
result.append(sorted.pop())
result.append(sorted.pop())
}
return result
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ------------------------------------------
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
result.append(sorted.pop()) // value of type '[Int]' has no member 'pop'
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
for _ in 1...lst.count {
result.sort()
result.reverse()
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
var result = lst
for _ in 1...lst.count {
result.sort()
result.reverse()
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
func reverseString(str: String) -> String {
return String(str.reversed())
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// Example:
// reverseString("hello") == "olleh"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// -----------------------------------------------------------------------------
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
func changeCase(str: String) -> String {
let arr = str.split(separator: " ")
var newArr = [String]()
for i in arr {
if i.isEmpty {
continue
}
newArr.append(i.capitalized)
}
return newArr.joined(separator: " ")
}
func stringTimes(str: String, n: Int) -> String {
var newStr = ""
for i in 1...n {
newStr += str
}
return newStr
}
func isPalindrome(str: String) -> Bool {
var newStr = ""
for i in str.reversed() {
newStr += i
}
return newStr == str
}
func transform(str: String) -> String {
var newStr = ""
for i in str.split(separator: " ") {
if i.isEmpty {
continue
}
newStr += i.capitalized
}
return newStr
}
func difference(nums: [Int]) -> Int {
var min = nums[0]
var max = nums[0]
for i in nums {
if i < min {
min = i
}
if i > max {
max = i
}
}
return max - min
}
func average(nums: [Int]) -> Double {
var sum = 0
for i in nums {
sum += i
}
return Double(sum) / Double(nums.count)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
// 2. Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case " ==> "hELLO cASE "
// " " ==> ""
func changeCase(str: String) -> String {
let arr = str.split(separator: " ")
var newArr = [String]()
for i in arr {
if i.isEmpty {
continue
}
newArr.append(i.capitalized)
}
return newArr.joined(separator: " ")
}
// 3. Given a string and an integer, n, return a string that is n copies of the input string.
// Example:
// stringTimes("Hi", 2) == "HiHi"
// stringTimes("Hi", 3) == "HiHiHi"
// stringTimes("Hi", 1) == "Hi"
func stringTimes(str: String, n: Int) -> String {
var newStr = ""
for i in 1...n {
newStr += str
}
return newStr
}
// 4. Given a string, return true if it is a palindrome.
// Example:
// isPalindrome("abba") == true
// isPalindrome("abcba") == true
// isPalindrome("peter") == false
func isPalindrome(str: String) -> Bool {
var newStr = ""
for i in str.reversed() {
newStr += i
}
return newStr == str
}
// 5. Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case " ==> "hELLO cASE "
// " " ==> ""
func transform(str: String) -> String {
var newStr = ""
for i in str.split(separator: " ") {
if i.isEmpty {
continue
}
newStr += i.capitalized
}
return newStr
}
// 6. Given an array of numbers, return the difference between the largest and smallest values.
// Example:
// difference([10, 15, 20, 2, 6]) == 18
// difference([-3, 4, -9, -1, -2, 15]) == 24
func difference(nums: [Int]) -> Int {
var min = nums[0]
var max = nums[0]
for i in nums {
if i < min {
min = i
}
if i > max {
max = i
}
}
return max - min
}
// 7. Given an array of numbers, return the average number.
// Example:
// average([1, 5, 87, 45, 8, 8]) == 25
// average([9, 47, 23, 95, 16, 52]) == 40
func average(nums: [Int]) -> Double {
var sum = 0
for i in nums {
sum += i
}
return Double(sum) / Double(nums.count)
}
// 8. Given
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
for i in 1...n { // immutable value 'i' was never used; consider replacing with '_' or removing it
newStr += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 2. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example:
// nums = [1,2,3,1,1,3]
// Output: 4
// Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example:
// nums = [1,3,2,3,1]
// Output: 2
// Explanation:
// There are 2 reverse pairs in nums:
// (1, 2) , (2, 4) .
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example:
// nums = [1,3,2,3,1]
// Output: 2
// Explanation:
// There are 2 reverse pairs in nums:
// (1, 2) , (2, 4) .
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example:
// nums = [1,3,2,3,1]
// Output: 2
// Explanation:
//
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let p = (a + b + c) / 2
return sqrt(p * (p - a) * (p - b) * (p - c))
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let p = (a + b + c) / 2
return sqrt(p * (p - a) * (p - b) * (p - c))
} else {
return -1
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
return sqrt(p * (p - a) * (p - b) * (p - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || c + a <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char == " " {
result += " "
} else {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
}
return result
}
func isPalindrome(input: String) -> Bool {
var left = 0
var right = input.length - 1
while left < right {
if input[left] != input[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || c + a <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
// -----------------------------------------------------------------------------
// 1.10.2
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to
// lower case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case-Sensitive " ==> "sENSEITaS eLCeH"
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char == " " {
result += " "
} else {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.10.3
// Given a string, return the boolean True if it is a palindrome, and False
// otherwise.
// A palindrome is a word that's the same forwards and backwards.
// Example:
// isPalindrome("racecar") == True
// isPalindrome("hello") == False
func isPalindrome(input: String) -> Bool {
var left = 0
var right = input.length - 1
while left < right {
if input[left] != input[right] {
return false
}
left += 1
right -= 1
}
return true
}
// -----------------------------------------------------------------------------
// 1.10.4
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to
// lower case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case-Sensitive " ==> "sENSEITaS eLCeH"
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char == " " {
result += " "
} else {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.10.5
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to
// lower case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello Case-Sensitive " ==> "sENSEITaS eLCeH"
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char == " " {
result += " "
} else {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
}
return result
}
// -----------------------------------------------------------------------------
//
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lower // value of type 'Character' has no member 'lower'
result += char.upper // value of type 'Character' has no member 'upper'
var right = input.length - 1 // value of type 'String' has no member 'length'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b > c && b + c > a && c + a > b {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
} else {
return -1
}
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given a string, return the string reversed.
// Example:
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.3
// Given a string, return true if the string is a palindrome.
// A palindrome is a word, phrase, number, or other sequence of characters
// which reads the same backward as forward.
// Example:
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.4
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.5
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.6
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.7
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.8
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.9
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverseCharacters("hello") == "olleh"
func reverseCharacters(string: String) -> String {
return string.map(String.init).reversed().join()
}
// -----------------------------------------------------------------------------
// 1.1.10
// Given a string, return a new string with the reversed order of characters.
// Example:
// reverse
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string == string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string.map(String.init).reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
} else {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
}
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var j = i + 1
while j < input.count && Character(input[j]).isDigit {
j += 1
}
sum += Int(input[i..<j])
i = j
} else {
i += 1
}
}
return sum
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
} else {
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
}
// -----------------------------------------------------------------------------
// 2. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var j = i + 1
while j < input.count && Character(input[j]).isDigit {
j += 1
}
sum += Int(input[i..<j])
i = j
} else {
i += 1
}
}
return sum
}
// -----------------------------------------------------------------------------
// 3. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var j = i + 1
while j < input.count && Character(input[j]).isDigit {
j += 1
}
sum += Int(input[i..<j])
i = j
} else {
i += 1
}
}
return sum
}
// -----------------------------------------------------------------------------
// 4. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(input: String) -> Int {
var sum = 0
var i = 0
while i < input.count {
if Character(input[i]).isDigit {
var j = i + 1
while j < input.count && Character(input[j]).isDigit {
j += 1
}
sum += Int(input[i..<j])
i = j
} else {
i += 1
}
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
if Character(input[i]).isDigit { // missing argument label 'extendedGraphemeClusterLiteral:' in call
if Character(input[i]).isDigit { // value of type 'Character' has no member 'isDigit'
while j < input.count && Character(input[j]).isDigit { // value of type 'Character' has no member 'isDigit'
while j < input.count && Character(input[j]).isDigit { // missing argument label 'extendedGraphemeClusterLiteral:' in call
sum += Int(input[i..<j]) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
if q.count == 2 {
return q[0] + q[1] <= w
}
if q.count == 3 {
return q[0] + q[1] + q[2] <= w && q[0] + q[1] <= w
}
return false
}
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
if q.count == 2 {
return q[0] + q[1] <= w
}
if q.count == 3 {
return q[0] + q[1] + q[2] <= w && q[0] + q[1] <= w
}
return false
}
// 2.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// 3.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// 4.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// 5.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// 6.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// 7.
// Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
if s[i..<i+3] == "code" { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w {
return true
}
var q2 = q.reversed()
var sum2 = 0
for i in q2 {
sum2 += i
}
if sum2 <= w {
return true
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w {
return true
}
var q2 = q.reversed()
var sum2 = 0
for i in q2 {
sum2 += i
}
if sum2 <= w {
return true
}
return false
}
// 2.
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w {
return true
}
var q2 = q.reversed()
var sum2 = 0
for i in q2 {
sum2 += i
}
if sum2 <= w {
return true
}
return false
}
// 3.
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum <= w {
return true
}
var q2 = q.reversed()
var sum2 = 0
for i in q2 {
sum2 += i
}
if sum2 <= w {
return true
}
return false
}
// 4.
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3,
var q2 = q.reversed() // variable 'q2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, { (sum, element) -> Int in
if sum + element > w {
return sum
} else {
return sum + element
}
}) == 0
}
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return q.reduce(0, { (sum, element) -> Int in
if sum + element > w {
return sum
} else {
return sum + element
}
}) == 0
}
// -----------------------------------------------------------------------------
// 10. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 11. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 12. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 13. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 14. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 15. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 16. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 17. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, { (sum, element) -> Int in
return sum + element
})
}
// -----------------------------------------------------------------------------
// 18. Write a function that returns the sum of the elements of an array.
// Example:
// sum([1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, {
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
return q.count == 1 || q.count == 2 ? q.sum() <= w : q.count == 3 && q.sum() <= w && q.max() <= w
}
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return q.count == 1 || q.count == 2 ? q.sum() <= w : q.count == 3 && q.sum() <= w && q.max() <= w
}
// 2.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 3.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 4.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 5.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 6.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 7.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 8.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 9.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x })
}
// 10.
// Write a function that returns the sum of the elements of the array a.
// If the array is empty, the function should return 0.
// Example:
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(a: [Int]) -> Int {
return a.count == 0 ? 0 : a.reduce(0
return q.count == 1 || q.count == 2 ? q.sum() <= w : q.count == 3 && q.sum() <= w && q.max() <= w // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return q.count == 1 || q.count == 2 ? q.sum() <= w : q.count == 3 && q.sum() <= w && q.max() <= w // value of type '[Int]' has no member 'sum'
return q.count == 1 || q.count == 2 ? q.sum() <= w : q.count == 3 && q.sum() <= w && q.max() <= w // value of type '[Int]' has no member 'sum'
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // extra argument in call
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // string interpolation can only appear inside a string literal
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // cannot find 'x' in scope
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // expected ',' separator
return a.count == 0 ? 0 : a.reduce(0, \(sum, x) { sum + x }) // cannot find 'x' in scope
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
return isPalindromic(q)
}
func isPalindromic(_ q: [Int]) -> Bool {
var i = 0
var j = q.count - 1
while i < j {
if q[i] != q[j] {
return false
}
i += 1
j -= 1
}
return true
}
import Foundation
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
return isPalindromic(q)
}
func isPalindromic(_ q: [Int]) -> Bool {
var i = 0
var j = q.count - 1
while i < j {
if q[i] != q[j] {
return false
}
i += 1
j -= 1
}
return true
}<|endoftext|>//
// main.swift
// 111
//
// Created by 임현석 on 2022/02/03.
//
import Foundation
// 111. 최대 증가 부분 수열
// https://www.acmicpc.net/problem/11053
let input = try! readLine()!
let n = Int(input)
let arr = [0] + [Int(c)! for c in readLine()!.split(separator: " ")]
let dp = [0] * (n + 1)
for i in 1...n {
for j in 1...i {
if arr[j] < arr[i] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
}
print(max(dp))<|endoftext|>//
// main.swift
// 110
//
// Created by 임현석 on 2022/02/03.
//
import Foundation
// 110. 최대 증가 부분 수열
// https://www.acmicpc.net/problem/11053
let input = try! readLine()!
let n = Int(input)
let arr = [Int(c)! for c in readLine()!.split(separator: " ")]
var dp = [1] * n
for i in 1...n {
for j in 1...i {
if arr[j - 1] < arr[i] {
dp[i] = max(dp[i], dp[j - 1] + 1)
}
}
}
print(max(dp))<|endoftext|>//
// main.swift
// 111
//
// Created by 임현석 on 2022/02/03.
//
import Foundation
// 111. 최대 증가 부분 수열
// https://www.acmicpc.net/problem/11053
let input = try! readLine()!
let n = Int(input)
let arr = [Int(c)! for c in readLine()!.split(separator: " ")]
var dp = [1] * n
for i in 1...n {
for j in 1...i {
if arr[j - 1] < arr[i] {
dp[i] = max(dp[i], dp[j - 1] + 1)
}
}
}
print(max(dp))<|endoftext|>//
// main.swift
// 111
//
// Created by 임현석 on 2022/02/03.
//
import Foundation
// 111. 최대 증가 부분 수열
// https://www.acmicpc.net/problem/11053
let input = try! readLine()!
let n = Int(input)
let arr = [Int(c)
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] == q[right] {
left += 1
right -= 1
} else {
return false
}
}
return true
}
import Foundation
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] == q[right] {
left += 1
right -= 1
} else {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 1206
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1208
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1209
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1210
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1211
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1212
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1213
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>//
// main.swift
// 1214
//
// Created by 임명호 on 2021/09/09.
//
import Foundation
var input = Array(UInt8(readLine()!)!)
var result = 0
for i in input {
if i == 49 {
result += 1
}
}
print(result)<|endoftext|>
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
var leftSum = 0
var rightSum = 0
while left < right {
leftSum += q[left]
rightSum += q[right]
left += 1
right -= 1
}
if leftSum == rightSum {
return true
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
var leftSum = 0
var rightSum = 0
while left < right {
leftSum += q[left]
rightSum += q[right]
left += 1
right -= 1
}
if leftSum == rightSum {
return true
}
return false
}
// 2.
// Given a string s, find the length of the longest substring without repeating characters.
// Example 1:
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: s = "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: s = "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
// Example 4:
// Input: s = ""
// Output: 0
// Constraints:
// 0 <= s.length <= 5 * 104
// s consists of English letters, digits, symbols and spaces.
// 3.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
// 4.
// Given an integer array nums, return the length of the longest strictly increasing subsequence.
// A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
// Example 1:
// Input: nums = [10,9,2,5,3,7,101,18]
// Output: 4
// Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
// Example 2:
// Input: nums = [0,1,0,3,2,3]
// Output: 4
// Example 3:
// Input: nums = [7,7,7,7,7,7,7]
// Output: 1
// Constraints:
// 1 <= nums.length <= 2500
// -104 <= nums[i] <= 104
// Follow up:
// Could you come up with the O(n2) solution?
// Could you come up with the O(n log(n)) solution using only constant space complexity?
// 5.
// Given an integer array nums, return the length of the longest strictly increasing subsequence.
// A subsequence is a sequence that can be derived from an array by deleting some or
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
return isPalindromic(q)
}
func isPalindromic(q: [Int]) -> Bool {
var i = 0
var j = q.count - 1
while i < j {
if q[i] != q[j] {
return false
}
i += 1
j -= 1
}
return true
}
import Foundation
func solution(n: Int) -> Int {
var answer = 0
var arr = [Int]()
for i in 1...n {
arr.append(i)
}
for i in 1...n {
var sum = 0
for j in 1...n {
sum += arr[j-1]
if sum > n {
break
}
if sum == n {
answer += 1
break
}
}
}
return answer
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
return isPalindromic(q)
}
func isPalindromic(q: [Int]) -> Bool {
var i = 0
var j = q.count - 1
while i < j {
if q[i] != q[j] {
return false
}
i += 1
j -= 1
}
return true
}<|endoftext|>//
// main.swift
// 11000
//
// Created by 윤승현 on 2021/04/17.
//
import Foundation
func solution(n: Int) -> Int {
var answer = 0
var arr = [Int]()
for i in 1...n {
arr.append(i)
}
for i in 1...n {
var sum = 0
for j in 1...n {
sum += arr[j-1]
if sum > n {
break
}
if sum == n {
answer += 1
break
}
}
}
return answer
}
print(solution(15))<|endoftext|>//
// main.swift
// 11000
//
// Created by 윤승현 on 2021/04/17.
//
import Foundation
func solution(n: Int) -> Int {
var answer = 0
var arr = [Int]()
for i in 1...n {
arr.append(i)
}
for i in 1...n {
var sum = 0
for j in 1...n {
sum += arr[j-1]
if sum > n {
break
}
if sum == n {
answer += 1
break
}
}
}
return answer
}
print(solution(15))<|endoftext|>//
// main.swift
// 11000
//
// Created by 윤승현 on 2021/04/17.
//
import Foundation
func solution(n: Int) -> Int {
var answer = 0
var arr = [Int]()
for i in 1...n {
arr.append(i)
}
for i in 1...n {
var sum = 0
for j in 1...n {
sum += arr[j-1]
if sum > n {
break
}
if sum == n {
answer += 1
break
}
}
}
return answer
}
print(solution(15))<|endoftext|>//
// main.swift
// 11000
//
// Created by 윤승현 on 2021/04/17.
//
import Foundation
func solution(n: Int) -> Int {
var answer = 0
var arr = [Int]()
for i in 1...n {
arr.append(i)
}
for i in 1...n {
var sum = 0
for j in 1...n {
sum += arr[j-1]
if sum > n {
break
}
if sum == n {
answer += 1
break
}
}
}
return answer
}
print(solution(15))<|endoftext|>//
// main.swift
// 11000
//
// Created by 윤승현 on 2021/04/17.
//
return isPalindromic(q) // missing argument label 'q:' in call
for i in 1...n { // immutable value 'i' was never used; consider replacing with '_' or removing it
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
return q.reduce(0, { $0 + $1 }) <= w && isPalindromic(q)
}
func isPalindromic(_ q: [Int]) -> Bool {
return q.reversed() == q
}
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
func equalIsNot(s: String) -> Bool {
return s.count("is") == s.count("not")
}
func sumNumbers(s: String) -> Int {
var sum = 0
for c in s {
if Character.isDigit(c) {
sum += Int(c)
}
}
return sum
}
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
if q.count == 1 {
return q[0] <= w
}
return q.reduce(0, { $0 + $1 }) <= w && isPalindromic(q)
}
func isPalindromic(_ q: [Int]) -> Bool {
return q.reversed() == q
}
// -----------------------------------------------------------------------------
// 2. Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// Example:
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i..<i+3] == "code" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Given a string, return true if the number of appearances of "is" anywhere in the string is equal to the number of appearances of "not" anywhere in the string (case sensitive).
// Example:
// equalIsNot("This is not") → false
// equalIsNot("This is notnot") → true
// equalIsNot("noisxxnotyynotxisi") → true
func equalIsNot(s: String) -> Bool {
return s.count("is") == s.count("not")
}
// -----------------------------------------------------------------------------
// 4. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
// Example:
// sumNumbers("abc123xyz") → 123
// sumNumbers("aa11b33") → 44
// sumNumbers("7 11") → 18
func sumNumbers(s: String) -> Int {
var sum = 0
for c in s {
if Character.isDigit(c) {
sum += Int(c)
}
}
return sum
}
// -----------------------------------------------------------------------------
// 5. Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
// Example:
// stringBits("Hello") → "Hlo"
// stringBits("Hi") → "H"
// stringBits("Heeololeo") → "Hello"
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Given a non-empty string like "Code" return a string like "CCoCodCode".
// Example:
// stringSplosion("Code") → "CCoCodCode"
// stringSplosion("abc") → "aababc"
// stringSplosion("ab") → "aab"
func stringSplosion(s: String) -> String {
var result = ""
for i in 0..<s.count {
result += s[0..<i+1]
}
if s[i..<i+3] == "code" { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return s.count("is") == s.count("not") // cannot call value of non-function type 'Int'
return s.count("is") == s.count("not") // cannot call value of non-function type 'Int'
if Character.isDigit(c) { // type 'Character' has no member 'isDigit'
sum += Int(c) // no exact matches in call to initializer
result += s[i] // no exact matches in call to subscript
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] == q[right] {
left += 1
right -= 1
} else {
return false
}
}
return true
}
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
var sum = 0
for i in q {
sum += i
}
if sum > w {
return false
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] == q[right] {
left += 1
right -= 1
} else {
return false
}
}
return true
}
// 10. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 11. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 12. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 13. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 14. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 15. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 16. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 17. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// 18. Write a function that returns the sum of the elements of an array of integers.
// Example:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
var sum = 0
func smallestChange(arr: [Int]) -> Int {
var min = Int.max
for i in 0..<arr.count {
for j in 0..<arr.count {
if i != j {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
var count = 0
for k in 0..<arr.count / 2 {
if arr[k] != arr[arr.count - 1 - k] {
count += 1
}
}
min = min < count ? min : count
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return min
}
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
func differenceMaxMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
return max - min
}
func checkForZero(arr: [Int]) -> Bool {
for i in 0..<arr.count {
if arr[i] == 0 {
for j in i..<arr.count {
if arr[j] == 1 {
return true
}
}
}
}
return false
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var min = Int.max
for i in 0..<arr.count {
for j in 0..<arr.count {
if i != j {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
var count = 0
for k in 0..<arr.count / 2 {
if arr[k] != arr[arr.count - 1 - k] {
count += 1
}
}
min = min < count ? min : count
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return min
}
// 14. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, -2, 3, -1, 5]) == 10
// sumOfPositives([-1, 2, 3, -1, -5]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
// 15. Given an array of integers, return the difference between the largest and smallest integers in the array.
// For example:
// differenceMaxMin([10, 4, 1, 4, -10, -50, 32, 21]) == 82
// differenceMaxMin([44, 32, 86, 19]) == 67
func differenceMaxMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
return max - min
}
// 16. Given an array of integers, return true if the array contains a 0 with a 1 somewhere later in the array.
// For example:
// checkForZero([1, 1, 1, 0, 1, 1, 1]) == true
// checkForZero([1, 1, 1, 1, 1]) == false
// checkForZero([1, 0, 1, 1, 1]) == true
// checkForZero([1, 1, 1]) == false
func checkForZero(arr: [Int]) -> Bool {
for i in 0..<arr.count {
if arr[i] == 0 {
for j in i..<arr.count {
if arr[j] == 1 {
return true
}
}
}
}
return false
}
// 17. Given an array of integers, return the difference between the largest and smallest integers in the array.
// However, the larger of the two differences is not allowed to be less than 10.
// For example:
// LargestDifference([1, 2, 3, 4, 5, 10, 11]) == 9
// LargestDifference([1, 5, 10, 14]) == 13
// LargestDifference([1, 2]) == 1
// LargestDifference([1, 2, 3, 4, 100]) == 96
// LargestDifference([1, 2, 3, 4, 9, 10]) == 9
// LargestDifference([1, 2, 3, 4, 9, 10, 11]) == 9
// LargestDifference([1, 2, 3,
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
arr[j] = temp // cannot assign through subscript: 'arr' is a 'let' constant
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
arr[j] = temp // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
func difference(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
// 2. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, 2, 3, -1, -2]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
// 3. Given an array of integers, return the difference between the largest and smallest integers in the array.
// For example:
// difference([1, 2, 3, 4, 5]) == 4
// difference([1, 2, 3, -4, 5]) == 9
// difference([1, 2, 3, -4, -5]) == 9
// difference([-5, -1, -7, -2]) == 13
func difference(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
// 4. Given an array of integers, return the mean (average) of the integers.
// For example:
// mean([1, 2, 3, 4, 5]) == 3
// mean([1, 2, 3, 4, 5, 6]) == 3.5
// mean([1, 2, 3, 4, 5, 6, 7]) == 4
// mean([1, 2, 3, 4, 5, 6, 7, 8]) == 5
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 6
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 7
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 8
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 9
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 10
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 11
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 12
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 13
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 14
// mean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
func firstRecurringCharacter(s: String) -> String? {
var seen = [Character]()
for c in s {
if seen.contains(c) {
return String(c)
} else {
seen.append(c)
}
}
return nil
}
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
func difference(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
func has33(arr: [Int]) -> Bool {
for i in arr {
if i == 3 {
if arr.contains(3) {
return true
}
}
}
return false
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
// 2. Given a string, return the first recurring character in it, or null if there is no recurring
// character.
// For example:
// firstRecurringCharacter("abcd") == null
// firstRecurringCharacter("abcdabcd") == "d"
// firstRecurringCharacter("abcdabcde") == "d"
// firstRecurringCharacter("abcde") == null
func firstRecurringCharacter(s: String) -> String? {
var seen = [Character]()
for c in s {
if seen.contains(c) {
return String(c)
} else {
seen.append(c)
}
}
return nil
}
// 3. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, 2, 3, -1, -2]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
// 4. Given an array of integers, return the difference between the largest and smallest integers in the array.
// For example:
// difference([1, 2, 3, 4, 5]) == 4
// difference([1, 2, 3, -4, 5]) == 7
// difference([1, 2, 3, -4, -5]) == 8
// difference([-1, -2, -3, -4, -5]) == 8
// difference([1, 2, 3, 4, 5, 6]) == 5
// difference([1, 2, 3, 4, 5, 0]) == 5
// difference([1, 2, 3, 4, 5, -6]) == 11
func difference(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
for i in arr {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
// 5. Given an array of integers, return true if the array contains a 3 next to a 3 somewhere.
// For example:
// has33([1, 3, 3]) == true
// has33([1, 3, 1, 3]) == true
// has33([3, 2, 5, 3]) == true
// has33([3, 2, 1, 3]) == false
// has33([3, 2, 3, 7]) == false
// has33([3, 3, 8, 3]) == false
func has33(arr: [Int]) -> Bool {
for i in arr {
if i == 3 {
if arr.contains(3) {
return true
}
}
}
return false
}
// 6. Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere.
// For example:
// array123([1, 2, 3, 1, 2, 3]) == true
// array123([1, 1, 2, 3, 1, 2, 3]) == true
// array123([1, 1, 2, 4, 1,
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var min = Int.max
for i in 0..<arr.count {
var count = 0
for j in 0..<arr.count {
if i != j {
if arr[i] != arr[j] {
count += 1
}
}
}
if count < min {
min = count
}
}
return min
}
func sumNumbers(s: String) -> Int {
var sum = 0
for c in s {
if Character.isDigit(c) {
sum += Int(c)
}
}
return sum
}
func arrayFront9(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 9 {
return true
}
if i >= 3 {
break
}
}
return false
}
func array123(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 1 {
if i + 2 >= nums.count {
return false
}
if nums[i + 1] == 2 && nums[i + 2] == 3 {
return true
}
}
}
return false
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var min = Int.max
for i in 0..<arr.count {
var count = 0
for j in 0..<arr.count {
if i != j {
if arr[i] != arr[j] {
count += 1
}
}
}
if count < min {
min = count
}
}
return min
}
// ----------------------------------------------------------------------------------------------------------------------
// 10. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0' to '9'. String.charAt(int) returns the char at the given index.)
// sumNumbers("abc123xyz") → 123
// sumNumbers("aa11b33") → 44
// sumNumbers("7 11") → 18
func sumNumbers(s: String) -> Int {
var sum = 0
for c in s {
if Character.isDigit(c) {
sum += Int(c)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.
// arrayFront9([1, 2, 9, 3, 4]) → true
// arrayFront9([1, 2, 3, 4, 9]) → false
// arrayFront9([1, 2, 3, 4, 5]) → false
func arrayFront9(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 9 {
return true
}
if i >= 3 {
break
}
}
return false
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere.
// array123([1, 1, 2, 3, 1]) → true
// array123([1, 1, 2, 4, 1]) → false
// array123([1, 1, 2, 1, 2, 3]) → true
func array123(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 1 {
if i + 2 >= nums.count {
return false
}
if nums[i + 1] == 2 && nums[i + 2] == 3 {
return true
}
}
}
return false
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
// stringMatch("xxcaazz", "xxbaaz") → 3
// stringMatch("abc", "abc") → 2
// stringMatch("abc", "axc") → 0
func stringMatch(a: String, b: String)
if Character.isDigit(c) { // type 'Character' has no member 'isDigit'
sum += Int(c) // no exact matches in call to initializer
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
}
left += 1
right -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
}
left += 1
right -= 1
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1
// Given two strings, write a method to decide if one is a permutation of the other.
// A permutation is defined as a string that is formed by rearranging the characters of a different string.
// For example, "abc" and "cba" are permutations of each other, but "abc" and "cbd" are not.
// Assume the strings are case-sensitive.
// Assume the strings only contain letters.
// Assume the strings are ASCII.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
// Assume the strings are not empty.
// Assume the strings are not null.
//
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
func longestSubarrayOfSumZero(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var sum = 0
while right < arr.count {
sum += arr[right]
while sum > 0 {
sum -= arr[left]
left += 1
}
count = max(count, right - left + 1)
right += 1
}
return count
}
func longestSubarrayOfSameElements(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var prev = 0
while right < arr.count {
if arr[right] != prev {
count = max(count, right - left)
left = right
}
prev = arr[right]
right += 1
}
return max(count, right - left)
}
func longestSubarrayInAscendingOrder(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var prev = 0
while right < arr.count {
if arr[right] < prev {
count = max(count, right - left)
left = right
}
prev = arr[right]
right += 1
}
return max(count, right - left)
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
// 2. Given an array of integers, find the length of the longest subarray where the sum of all the elements in the subarray is equal to zero.
// For example:
// longestSubarrayOfSumZero([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5
// longestSubarrayOfSumZero([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 11
// longestSubarrayOfSumZero([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 12
func longestSubarrayOfSumZero(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var sum = 0
while right < arr.count {
sum += arr[right]
while sum > 0 {
sum -= arr[left]
left += 1
}
count = max(count, right - left + 1)
right += 1
}
return count
}
// 3. Given an array of integers, find the length of the longest subarray where all the elements in the subarray are the same.
// For example:
// longestSubarrayOfSameElements([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1
// longestSubarrayOfSameElements([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 1
// longestSubarrayOfSameElements([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 12
func longestSubarrayOfSameElements(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var prev = 0
while right < arr.count {
if arr[right] != prev {
count = max(count, right - left)
left = right
}
prev = arr[right]
right += 1
}
return max(count, right - left)
}
// 4. Given an array of integers, find the length of the longest subarray where all the elements in the subarray are in ascending order.
// For example:
// longestSubarrayInAscendingOrder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1
// longestSubarrayInAscendingOrder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 1
// longestSubarrayInAscendingOrder([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 12
func longestSubarrayInAscendingOrder(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = 0
var prev = 0
while right < arr.count {
if arr[right] < prev {
count = max(count, right - left)
left = right
}
prev = arr[right]
right += 1
}
return max(count, right - left)
}
// 5. Given an array of integers, find the length of the longest subarray
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] < arr[right] {
right -= 1
} else {
left += 1
}
} else {
left += 1
right -= 1
}
}
return count
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var count = 0
for i in 0..<sortedArr.count/2 {
if sortedArr[i] != sortedArr[sortedArr.count-1-i] {
count += 1
}
}
return count
}
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
func difference(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var min = arr[0]
var max = arr[0]
for i in arr {
if i < min {
min = i
}
if i > max {
max = i
}
}
return max - min
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var count = 0
for i in 0..<sortedArr.count/2 {
if sortedArr[i] != sortedArr[sortedArr.count-1-i] {
count += 1
}
}
return count
}
// 2. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, -2, 3, -1, 5]) == 10
// sumOfPositives([]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
// 3. Given an array of integers, return the difference between the largest and smallest integers in the array.
// For example:
// difference([1, 2, 3, 4, 5]) == 4
// difference([1, 2, 3, -4, 5]) == 10
// difference([1, 2, 3, -4, 5, 0]) == 10
// difference([1, 2, 3, -4, 5, 0, 5]) == 10
// difference([1, -2, 3, -4, 5, 0, 5]) == 10
// difference([1, 2, 3, 4, 5, 10]) == 9
// difference([-1, -2, -3, -4, -5]) == 1
// difference([]) == nil
func difference(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var min = arr[0]
var max = arr[0]
for i in arr {
if i < min {
min = i
}
if i > max {
max = i
}
}
return max - min
}
// 4. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, -2, 3, -1, 5]) == 10
// sumOfPositives([]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
// 5. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, -2, 3, -1, 5]) == 10
// sumOfPositives([]) == 0
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i > 0 {
sum += i
}
}
return sum
}
// 6. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sumOfPositives([1, 2, 3, -1, 5]) == 9
// sumOfPositives([-1, 2, 3, -1, 5]) == 10
// sumOfPositives([-1, -2, 3, -1, 5]) == 10
// sumOfPositives([]) == 0
func sumOfPositives(arr: [Int]) -> Int {
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var result = []
for i in lst2 {
if i.count < total {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var result = []
for i in lst2 {
if i.count < total {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if !result.contains(i) {
result.append(i)
}
}
return result
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { (sum, number) -> Int in
return sum + number
})
}
func avg(numbers: [Int]) -> Int {
return sum(numbers) / numbers.count
}
func highest(numbers: [Int]) -> Int {
return numbers.max() ?? 0
}
func lowest(numbers: [Int]) -> Int {
return numbers.min() ?? 0
}
func smallest(numbers: [Int]) -> Int {
return lowest(numbers)
}
func largest(numbers: [Int]) -> Int {
return highest(numbers)
}
func secondLargest(numbers: [Int]) -> Int {
return numbers.sorted().last!
}
func secondSmallest(numbers: [Int]) -> Int {
return numbers.sorted().first!
}
func smallest(numbers: [Int]) -> Int {
return numbers.sorted().first!
}
func largest(numbers: [Int]) -> Int {
return numbers.sorted().last!
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if !result.contains(i) {
result.append(i)
}
}
return result
}
// 2. Write a function that accepts an array of numbers and returns the sum of the numbers.
// If the array is empty, it should return 0.
// Examples
// sum([1, 2, 3]) == 6
// sum([]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { (sum, number) -> Int in
return sum + number
})
}
// 3. Write a function that accepts an array of numbers and returns the average of the numbers.
// If the array is empty, it should return 0.
// Examples
// avg([1, 2, 3]) == 2
// avg([]) == 0
func avg(numbers: [Int]) -> Int {
return sum(numbers) / numbers.count
}
// 4. Write a function that accepts an array of numbers and returns the highest number.
// If the array is empty, it should return 0.
// Examples
// highest([1, 2, 3]) == 3
// highest([]) == 0
func highest(numbers: [Int]) -> Int {
return numbers.max() ?? 0
}
// 5. Write a function that accepts an array of numbers and returns the lowest number.
// If the array is empty, it should return 0.
// Examples
// lowest([1, 2, 3]) == 1
// lowest([]) == 0
func lowest(numbers: [Int]) -> Int {
return numbers.min() ?? 0
}
// 6. Write a function that accepts an array of numbers and returns the smallest number.
// If the array is empty, it should return 0.
// Examples
// smallest([1, 2, 3]) == 1
// smallest([]) == 0
func smallest(numbers: [Int]) -> Int {
return lowest(numbers)
}
// 7. Write a function that accepts an array of numbers and returns the largest number.
// If the array is empty, it should return 0.
// Examples
// largest([1, 2, 3]) == 3
// largest([]) == 0
func largest(numbers: [Int]) -> Int {
return highest(numbers)
}
// 8. Write a function that accepts an array of numbers and returns the second largest number.
// If the array is empty, it should return 0.
// Examples
// secondLargest([1, 2, 3]) == 2
// secondLargest([]) == 0
func secondLargest(numbers: [Int]) -> Int {
return numbers.sorted().last!
}
// 9. Write a function that accepts an array of numbers and returns the second smallest number.
// If the array is empty, it should return 0.
// Examples
// secondSmallest([1, 2, 3]) == 1
// secondSmallest([]) == 0
func secondSmallest(numbers: [Int]) -> Int {
return numbers.sorted().first!
}
// 10. Write a function that accepts an array of numbers and returns the smallest number.
// If the array is empty, it should return 0.
// Examples
// smallest([1, 2, 3]) == 1
// smallest([]) == 0
func smallest(numbers: [Int]) -> Int {
return numbers.sorted().first!
}
// 11. Write a function that accepts an array of numbers and returns the largest number.
// If the array is empty, it should return 0.
// Examples
// largest([1, 2, 3]) == 3
// largest([]) == 0
func largest(numbers: [Int]) -> Int {
return numbers.sorted().last!
}
// 12. Write a function that accepts an array of numbers and returns the second largest number.
// If the array is empty, it should return 0.
// Examples
// secondLargest([1, 2, 3]) == 2
// secondLargest([]) == 0
func secondLargest(numbers: [
return sum(numbers) / numbers.count // missing argument label 'numbers:' in call
return lowest(numbers) // missing argument label 'numbers:' in call
return highest(numbers) // missing argument label 'numbers:' in call
func smallest(numbers: [Int]) -> Int { // invalid redeclaration of 'smallest(numbers:)'
func largest(numbers: [Int]) -> Int { // invalid redeclaration of 'largest(numbers:)'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
// 2. Write a function that accepts an array of numbers and returns the sum of all the numbers.
// Examples
// sum([1, 2, 3, 4, 5]) == 15
// sum([1, 2, 3, 4, 5, 6]) == 21
// sum([1, 2, 3, 4, 5, 6, 7]) == 28
// sum([1, 2, 3, 4, 5, 6, 7, 8]) == 36
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 45
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 66
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 78
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 91
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 105
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 136
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 153
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 170
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 187
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == 204
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]) == 221
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var count = 0
var count2 = 0
for i in lst1 {
count += i.count
}
for i in lst2 {
count2 += i.count
}
if count == count2 {
return lst1
} else if count < count2 {
return lst1
} else {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var count = 0
var count2 = 0
for i in lst1 {
count += i.count
}
for i in lst2 {
count2 += i.count
}
if count == count2 {
return lst1
} else if count < count2 {
return lst1
} else {
return lst2
}
}
// 2. Write a function that accepts two arrays of numbers and returns the array with the
// largest sum. If the sums are equal, return the first array.
// Examples
// largestSum(lst1: [] as [Int], lst2: [] as [Int]) == [] as [Int]
// largestSum(lst1: [1, 2, 3], lst2: [1, 2, 3]) == [1, 2, 3]
// largestSum(lst1: [1, 2, 3], lst2: [1, 2, 3, 4]) == [1, 2, 3, 4]
// largestSum(lst1: [1, 2, 3], lst2: [1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
// largestSum(lst1: [1, 2, 3], lst2: [1, 2, 3, 4, 5, 6]) == [1, 2, 3, 4, 5, 6]
// largestSum(lst1: [1, 2, 3], lst2: [1, 2, 3, 4, 5, 6, 7]) == [1, 2, 3, 4, 5, 6, 7]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7]) == [1, 2, 3, 4, 5, 6, 7]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7, 8, 9]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
// largestSum(lst1: [1, 2, 3, 4, 5, 6, 7], lst2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
// largestSum(lst1: [1, 2, 3, 4, 5, 6,
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if !result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if !result.contains(i) {
result.append(i)
}
}
return result
}
// 2. Write a function that accepts a string and returns the number (count) of vowels contained within.
// Valid vowels are: a, e, i, o, u.
// A function can be implemented either using selection or iteration, but not both.
// Examples
// vowelCount("ciao") == 2
// vowelCount("vowel") == 2
// vowelCount("zodiac") == 1
// vowelCount("strength") == 2
// vowelCount("mischta") == 2
// vowelCount("") == 0
// vowelCount("aeiou") == 5
// vowelCount("why") == 0
// vowelCount("abracadabra") == 5
// vowelCount("bcd") == 0
// vowelCount("aeiouAEIOU") == 5
// vowelCount("12345") == 0
// vowelCount("🤟") == 0
//
// 3. Write a function that accepts a string and returns true if the string is a valid number (isNum).
// A valid number is a string that represents a positive integer or a positive floating-point number.
// Valid numbers include:
// 1. Numbers with no letters (e.g. 1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
// 2. Numbers with a single decimal point (e.g. 1.0, 2.5, 3.14159, 4.0000000001)
// 3. Numbers with a single exponent (e.g. 1e10, 2e-10, 3.14159e+3, 4.0000000001e-10)
// 4. Numbers with multiple decimal points (e.g. 1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var result = []
for i in lst2 {
if i.count < total {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var result = []
for i in lst2 {
if i.count < total {
result.append(i)
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
var result = [] as [String]
for i in lst1 {
total += i.count
}
for i in lst2 {
total += i.count
}
if total == lst1.count * lst2.count {
return lst1
} else if total == lst2.count * lst1.count {
return lst2
} else {
for i in lst1 {
if i.count < lst2.count {
result.append(i)
}
}
return result
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
var result = [] as [String]
for i in lst1 {
total += i.count
}
for i in lst2 {
total += i.count
}
if total == lst1.count * lst2.count {
return lst1
} else if total == lst2.count * lst1.count {
return lst2
} else {
for i in lst1 {
if i.count < lst2.count {
result.append(i)
}
}
return result
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for i in input {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" && i != "A" && i != "E" && i != "I" && i != "O" && i != "U" {
result += i
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
// 2. Write a function that accepts a string and returns a new string with all vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello") == " hll"
// removeVowels("cucumber") == " cmbtr"
// removeVowels("") == ""
// removeVowels("a") == ""
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("12345") == "12345"
// removeVowels("😀😁😂🤣😃😄😅😆😉😊😋😌😍😘😙😚😛😜😝😞😟😠😡😢😣😤😥😦😧😨😩😪😫😬😭😮😯😰😱😲😳😴😵😶😷😸😹😺😻😼😽😾😿🙀🙁🙃🙄🙅🙆🙇🙈🙉🙊🙋🙌🙍🙎🙏🙐🙑🙒🙓🙔🙕🙖🙗🙘🙙🙚🙛🙜🙝🙞🙟🙠🙡🙢🙣🙤🙥🙦🙧🙨🙩🙪🙫🙬🙭🙮🙯") == ""
func removeVowels(input: String) -> String {
var result = ""
for i in input {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" && i != "A" && i != "E" && i != "I" && i != "O" && i != "U" {
result += i
}
}
return result
}
// 3. Write a function that accepts a string and a single character, and returns an integer of how many times that character is found in the string.
// Examples
// strCount("Hello", "o") == 1
// strCount("Hello", "l") == 2
// strCount("Hello", "e") == 1
// strCount("Hello", "H") == 1
// strCount("Hello", "ll") == 2
// strCount("Hello", "He") == 1
// strCount("Hello", "eo") == 1
// strCount("Hello", "eHello") == 1
// strCount("Hello", "oHellllooo") == 3
// strCount("Hello", "oHelllloo") == 4
result += i // cannot convert value of type 'Character' to expected argument type 'String'
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var total2 = 0
for i in lst2 {
total2 += i.count
}
if total == total2 {
return lst1
} else if total > total2 {
return lst1
} else {
return lst2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var total = 0
for i in lst1 {
total += i.count
}
var total2 = 0
for i in lst2 {
total2 += i.count
}
if total == total2 {
return lst1
} else if total > total2 {
return lst1
} else {
return lst2
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = lst1
for i in lst2 {
if result.count < lst2.count {
result.append(i)
}
}
return result
}
// 2. Write a function that accepts an array of numbers and returns the sum of all the numbers.
// Examples
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4, 5]) == 15
// sum([-1, 2, 3]) == 2
// sum([]) == 0
// sum([-1, -2, -3]) == -6
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]) == -55
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15]) == -120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16]) == -120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17]) == -120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18]) == -120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19]) == -120
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == 120
// sum([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11,
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 1...a {
if isPrime(i) {
count += 1
}
}
return count == 3
}
func sumOfLowest3Numbers(numbers: [Int]) -> Int {
var lowest = numbers[0]
var secondLowest = numbers[1]
var thirdLowest = numbers[2]
var fourthLowest = numbers[3]
var sum = lowest + secondLowest + thirdLowest
for i in numbers {
if i < lowest {
lowest = i
}
if i < secondLowest {
secondLowest = i
}
if i < thirdLowest {
thirdLowest = i
}
if i < fourthLowest {
fourthLowest = i
}
}
sum += lowest
return sum
}
func firstNonRepeatingChar(s: String) -> Int {
for i in s {
if s.count(for: i) == 1 {
return s.firstIndex(for: i)!
}
}
return -1
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 1...a {
if isPrime(i) {
count += 1
}
}
return count == 3
}
// 2. Write a function that takes a number and returns the sum of the two lowest positive
// numbers given an array of minimum 4 positive integers.
// For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
// [10, 343445353, 3453445, 3453545353453] should return 3453455.
// Note: All array values are positive and will always be valid.
// Flags:
// 1. The array's length will always be at least 4.
// 2. Set a variable to hold the lowest number.
// 3. Set a variable to hold the second lowest number.
// 4. Set a variable to hold the third lowest number.
// 5. Set a variable to hold the fourth lowest number.
// 6. Set a variable to hold the sum of the lowest 3 numbers.
// 7. Loop through the array.
// 8. If the number is less than the lowest number, set the lowest number to the number.
// 9. If the number is less than the second lowest number, set the second lowest number to the number.
// 10. If the number is less than the third lowest number, set the third lowest number to the number.
// 11. If the number is less than the fourth lowest number, set the fourth lowest number to the number.
// 12. Add the lowest number to the sum of the lowest 3 numbers.
// 13. Return the sum of the lowest 3 numbers.
func sumOfLowest3Numbers(numbers: [Int]) -> Int {
var lowest = numbers[0]
var secondLowest = numbers[1]
var thirdLowest = numbers[2]
var fourthLowest = numbers[3]
var sum = lowest + secondLowest + thirdLowest
for i in numbers {
if i < lowest {
lowest = i
}
if i < secondLowest {
secondLowest = i
}
if i < thirdLowest {
thirdLowest = i
}
if i < fourthLowest {
fourthLowest = i
}
}
sum += lowest
return sum
}
// 3. Given a string, find the first non-repeating character in it and return it's index.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Flags:
// 1. Loop through the string.
// 2. If the character is not in the string, return the index.
// 3. If the character is in the string, return -1.
func firstNonRepeatingChar(s: String) -> Int {
for i in s {
if s.count(for: i) == 1 {
return s.firstIndex(for: i)!
}
}
return -1
}
// 4. Given a string, find the first character that is not repeated in it.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Flags:
// 1. Loop through the string.
// 2. If the character is not in the string, return the index.
// 3. If the character is in the string, return -1.
func firstNonRepeatingChar(s: String) -> Int {
for i in s {
if s.count(for: i) == 1 {
return s.firstIndex(for: i)!
}
}
return -1
}
// 5. Given a string, find the first character that is
if isPrime(i) { // cannot find 'isPrime' in scope
if s.count(for: i) == 1 { // cannot call value of non-function type 'Int'
return s.firstIndex(for: i)! // cannot convert return expression of type 'String.Index' to return type 'Int'
return s.firstIndex(for: i)! // incorrect argument label in call (have 'for:', expected 'of:')
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
var i = 2
while i < 100 {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
return true
} else {
return false
}
}
func sumDigits(a: Int) -> Int {
var sum = 0
var i = 0
while i < a {
sum += a % 10
a /= 10
i += 1
}
return sum
}
func factorial(a: Int) -> Int {
var sum = 1
var i = 1
while i <= a {
sum *= i
i += 1
}
return sum
}
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
var i = 2
while i < 100 {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
return true
} else {
return false
}
}
// 2. Write a function that takes a number and returns the sum of its digits.
// Example:
// sumDigits(10) == 1
func sumDigits(a: Int) -> Int {
var sum = 0
var i = 0
while i < a {
sum += a % 10
a /= 10
i += 1
}
return sum
}
// 3. Write a function that takes a number and returns the factorial of that number.
// Example:
// factorial(5) == 120
func factorial(a: Int) -> Int {
var sum = 1
var i = 1
while i <= a {
sum *= i
i += 1
}
return sum
}
// 4. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 5. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 6. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 7. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 8. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 9. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
a /= 10 // left side of mutating operator isn't mutable: 'a' is a 'let' constant
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
let factors = []
for i in 0..<primes.count {
if a % primes[i] == 0 {
factors.append(primes[i])
}
}
if factors.count == 3 {
return true
} else {
return false
}
}
func sumLowest(numbers: [Int]) -> Int {
let sortedNumbers = numbers.sorted()
return sortedNumbers[0] + sortedNumbers[1]
}
func maxProduct(numbers: [Int]) -> Int {
var maxProduct = 0
for i in 0..<numbers.count - 1 {
let product = numbers[i] * numbers[i + 1]
if product > maxProduct {
maxProduct = product
}
}
return maxProduct
}
func maxProduct3(numbers: [Int]) -> Int {
var maxProduct = 0
for i in 0..<numbers.count - 2 {
let product = numbers[i] * numbers[i + 1] * numbers[i + 2]
if product > maxProduct {
maxProduct = product
}
}
return maxProduct
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
let factors = []
for i in 0..<primes.count {
if a % primes[i] == 0 {
factors.append(primes[i])
}
}
if factors.count == 3 {
return true
} else {
return false
}
}
// 2. Write a function that takes a number and returns the sum of the two lowest positive numbers
// given an array of minimum 4 positive integers.
// 4 means that there are at least 4 positive integers.
// Example:
// [19, 5, 42, 2, 77] => 7
// [10, 343445353, 3453445, 3453545353453] => 34534555
func sumLowest(numbers: [Int]) -> Int {
let sortedNumbers = numbers.sorted()
return sortedNumbers[0] + sortedNumbers[1]
}
// 3. Given an array of integers , Find the maximum product you can get from multiplying 2 adjacent numbers in the array.
// Notes
// Array/list size is at least 2.
// Array/list numbers could be a mixture of positives, negatives also zeroes .
// Example
// [1, 2, 3] => 6
// [1, 2, 3, 4] => 8
// [3, 4, 5, 3, 1] => 24
// [-10, -3, -1, 2] => 30
func maxProduct(numbers: [Int]) -> Int {
var maxProduct = 0
for i in 0..<numbers.count - 1 {
let product = numbers[i] * numbers[i + 1]
if product > maxProduct {
maxProduct = product
}
}
return maxProduct
}
// 4. Given an array of integers , Find the maximum product you can get from multiplying 3 adjacent numbers in the array.
// Notes
// Array/list size is at least 3.
// Array/list numbers could be a mixture of positives, negatives also zeroes .
// Example
// [1, 2, 3, 4, 3, 2, 1, 1, 2, 3, 1, 2, 3, 4]
// The maximum product can be found when multiplying 3 consecutive numbers: 1,2,3,4,3,2,1
// Example solution:
// // Write your code here
// return 12
// The maximum product can be found when multiplying 3 consecutive numbers: 1,2,3,4,3,2,1
func maxProduct3(numbers: [Int]) -> Int {
var maxProduct = 0
for i in 0..<numbers.count - 2 {
let product = numbers[i] * numbers[i + 1] * numbers[i + 2]
if product > maxProduct {
maxProduct = product
}
}
return maxProduct
}
// 5. Given an array/list [] of integers , Find the Nth smallest element in this array of integers
// Notes
// Array/list size is at least 6 .
// Array/list's numbers could be a mixture of positives , negatives and zeros .
// Repetition of numbers in the array/list could occur , So (duplications) .
// Input >> Output Examples
// nthSmallest({34, 15, 88, 2} ,2) ==> return 15
// nthSmallest({15, 88, 2, 34, 15, 34} ,2) ==> return 2
// nthSmallest({34, 15, 88, 2, 15, 34, 2} ,1) ==> return 2
// nthSmallest({27, 19, 42, 2, 10, 48, 27, 19}
let factors = [] // empty collection literal requires an explicit type
factors.append(primes[i]) // cannot use mutating member on immutable value: 'factors' is a 'let' constant
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
var count = 0
for i in 1...a {
if isPrime(i) {
count += 1
}
}
if count >= 3 {
return true
}
}
return false
}
func countDigits(n: Int) -> Int {
return String(n).count
}
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
var count = 0
for i in 1...a {
if isPrime(i) {
count += 1
}
}
if count >= 3 {
return true
}
}
return false
}
// 2. Write a function that returns the number of digits of given integer.
// Example:
// countDigits(n: 1234) == 4
func countDigits(n: Int) -> Int {
return String(n).count
}
// 3. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 4. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 5. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 6. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 7. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 8. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 9. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 10. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 11. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 12. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 13. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 14. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 15. Convert a given number from base 10 to base 2.
// Example:
// toBinary(a: 10) == 1010
func toBinary(a: Int) -> Int {
return Int(a).toBinary()
}
// 16. Convert a given number from base 10 to base 2.
if isPrime(i) { // cannot find 'isPrime' in scope
return Int(a).toBinary() // value of type 'Int' has no member 'toBinary'
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
let count = 0
for i in 0..<a {
if a % i == 0 {
primes.append(i)
count += 1
}
}
if count == 3 {
return true
} else {
return false
}
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
let count = 0
for i in 0..<a {
if a % i == 0 {
primes.append(i)
count += 1
}
}
if count == 3 {
return true
} else {
return false
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------
primes.append(i) // cannot use mutating member on immutable value: 'primes' is a 'let' constant
count += 1 // left side of mutating operator isn't mutable: 'count' is a 'let' constant
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
var i = 2
while i < 100 {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
return true
} else {
return false
}
}
func sumDigits(a: Int) -> Int {
var sum = 0
var i = 0
while i < a {
sum += a % 10
a = a / 10
i += 1
}
return sum
}
func gcd(a: Int, b: Int) -> Int {
var i = 1
while i <= a && i <= b {
if a % i == 0 && b % i == 0 {
var gcd = i
}
i += 1
}
return gcd
}
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
var i = 2
while i < 100 {
if a % i == 0 {
count += 1
}
i += 1
}
if count == 3 {
return true
} else {
return false
}
}
// 2. Write a function that takes a number and returns the sum of its digits.
// Example:
// sumDigits(10) == 1
func sumDigits(a: Int) -> Int {
var sum = 0
var i = 0
while i < a {
sum += a % 10
a = a / 10
i += 1
}
return sum
}
// 3. Write a function that takes two numbers and returns the Greatest Common Divisor.
// Example:
// gcd(20, 30) == 10
func gcd(a: Int, b: Int) -> Int {
var i = 1
while i <= a && i <= b {
if a % i == 0 && b % i == 0 {
var gcd = i
}
i += 1
}
return gcd
}
// 4. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 5. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 6. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 7. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 8. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var i = 1
while i < a {
if a % i == 0 {
sum += i
}
i += 1
}
return sum
}
// 9. Write a function that takes a number and returns the sum of all its divisors except itself.
// Example:
// sumDivisors(12) == 1 + 2 + 3 + 4 + 6 + 12 == 30
func sumDivisors(a: Int) -> Int {
var sum = 0
var
a = a / 10 // cannot assign to value: 'a' is a 'let' constant
return gcd // cannot convert return expression of type '(Int, Int) -> Int' to return type 'Int'
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2...a {
if isPrime(i) {
count += 1
if count == 3 {
return true
}
}
}
return false
}
func number_of_digits(n: Int) -> Int {
return String(n).count
}
func numberToWords(num: Int) -> String {
var result = ""
var nums = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
var tens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
var tens2 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
var num = num
if num >= 1000000000 {
result += nums[num / 1000000000] + " Billion "
num %= 1000000000
}
if num >= 1000000 {
result += nums[num / 1000000] + " Million "
num %= 1000000
}
if num >= 1000 {
result += nums[num / 1000] + " Thousand "
num %= 1000
}
if num >= 100 {
result += nums[num / 100] + " Hundred "
num %= 100
}
if num >= 20 {
if num >= 10 {
result += tens2[num / 10 - 2] + " "
}
result += nums[num % 10]
} else if num > 0 {
result += tens[num]
}
return result.trim()
}
func firstUniqChar(s: String) -> Int {
var result = -1
var count = [Int](repeating: 0, count: 26)
for i in s {
count[i - "a"] += 1
}
for i in s {
if count[i - "a"] == 1 {
result = s.firstIndex(of: i)!
break
}
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2...a {
if isPrime(i) {
count += 1
if count == 3 {
return true
}
}
}
return false
}
// 2. Write a function that returns the number of digits of given integer.
// Example:
// number_of_digits(n: 348678) == 6
func number_of_digits(n: Int) -> Int {
return String(n).count
}
// 3. Convert a non-negative integer num to its English words representation.
// Example:
// numberToWords(num: 123) == "One Hundred Twenty Three"
func numberToWords(num: Int) -> String {
var result = ""
var nums = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
var tens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
var tens2 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
var num = num
if num >= 1000000000 {
result += nums[num / 1000000000] + " Billion "
num %= 1000000000
}
if num >= 1000000 {
result += nums[num / 1000000] + " Million "
num %= 1000000
}
if num >= 1000 {
result += nums[num / 1000] + " Thousand "
num %= 1000
}
if num >= 100 {
result += nums[num / 100] + " Hundred "
num %= 100
}
if num >= 20 {
if num >= 10 {
result += tens2[num / 10 - 2] + " "
}
result += nums[num % 10]
} else if num > 0 {
result += tens[num]
}
return result.trim()
}
// 4. Given a string s, find the first non-repeating character in it and return its index.
// If it does not exist, return -1.
// Example:
// firstUniqChar(s: "leetcode") == 0
// firstUniqChar(s: "loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var result = -1
var count = [Int](repeating: 0, count: 26)
for i in s {
count[i - "a"] += 1
}
for i in s {
if count[i - "a"] == 1 {
result = s.firstIndex(of: i)!
break
}
}
return result
}
// 5. Given a string s, find the first non-repeating character in it and return its index.
// If it does not exist, return -1.
// Example:
// firstUniqChar(s: "leetcode") == 0
// firstUniqChar(s: "loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var result = -1
var count = [Int](repeating: 0, count: 26)
for i in s {
count[i - "a"] += 1
}
for i in s {
if count[i - "a"] == 1 {
result = s.firstIndex(of
if isPrime(i) { // cannot find 'isPrime' in scope
return result.trim() // value of type 'String' has no member 'trim'
count[i - "a"] += 1 // binary operator '-' cannot be applied to two 'Character' operands
if count[i - "a"] == 1 { // binary operator '-' cannot be applied to two 'Character' operands
result = s.firstIndex(of: i)! // cannot assign value of type 'String.Index' to type 'Int'
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2..<a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
return true
} else {
return false
}
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2..<a {
if a % i == 0 {
count += 1
}
}
if count == 2 {
return true
} else {
return false
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2...a {
if isPrime(i) {
count += 1
}
if count == 3 {
return true
}
}
return false
}
func sumTwoSmallestNumbers(numbers: [Int]) -> Int {
var min1 = Int.max
var min2 = Int.max
for number in numbers {
if number < min1 {
min2 = min1
min1 = number
} else if number < min2 {
min2 = number
}
}
return min1 + min2
}
func findOdd(array: [Int]) -> Int {
var count = 0
for number in array {
for i in array {
if number == i {
count += 1
}
}
if count % 2 != 0 {
return number
}
count = 0
}
return 0
}
func findOdd2(array: [Int]) -> Int {
var count = 0
for number in array {
for i in array {
if number == i {
count += 1
}
}
if count % 2 != 0 {
return number
}
count = 0
}
return 0
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var count = 0
for i in 2...a {
if isPrime(i) {
count += 1
}
if count == 3 {
return true
}
}
return false
}
// 2. Write a function that takes a number and returns the sum of the two lowest positive
// numbers given an array of minimum 4 positive integers.
// For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
// [10, 343445353, 3453445, 3453545353453] should return 3453455.
// Note: All array values are positive and will always be valid.
// Multiples of 2 or 3 should not be counted as multipliers.
// Examples:
// sumTwoSmallestNumbers([5, 8, 12, 18, 22]) == 13
// sumTwoSmallestNumbers([7, 15, 12, 18, 22]) == 19
// sumTwoSmallestNumbers([25, 4, 2, 6, 10]) == 8
// sumTwoSmallestNumbers([15, 4, 10, 18, 22]) == 13
func sumTwoSmallestNumbers(numbers: [Int]) -> Int {
var min1 = Int.max
var min2 = Int.max
for number in numbers {
if number < min1 {
min2 = min1
min1 = number
} else if number < min2 {
min2 = number
}
}
return min1 + min2
}
// 3. Given an array of integers, find the one that appears an odd number of times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
func findOdd(array: [Int]) -> Int {
var count = 0
for number in array {
for i in array {
if number == i {
count += 1
}
}
if count % 2 != 0 {
return number
}
count = 0
}
return 0
}
// 4. Given an array of integers, find the one that appears an odd number of times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd).
func findOdd2(array: [Int]) -> Int {
var count = 0
for number in array {
for i in array {
if number == i {
count += 1
}
}
if count % 2 != 0 {
return number
}
count = 0
}
return 0
}
// 5. Given an array of integers, find the one that appears an odd number of times.
// There will
if isPrime(i) { // cannot find 'isPrime' in scope
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
let primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
var isPrime = true
for i in 0..<primeNumbers.count {
if primeNumbers[i] == a {
isPrime = true
break
} else {
isPrime = false
}
}
return isPrime
} else {
return false
}
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
let primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
var isPrime = true
for i in 0..<primeNumbers.count {
if primeNumbers[i] == a {
isPrime = true
break
} else {
isPrime = false
}
}
return isPrime
} else {
return false
}
}
print(isMultiplyPrime(a: 30))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(x))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(x))
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a", "e", "i", "o", and "u".
// The input string will only consist of lower case letters and/or spaces.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns the number of vowels
// in the string.
// Vowels are the letters "a
return Int(x) == pow(n, Int(x)) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return Int(x) == pow(n, Int(x)) // operator function '==' requires that 'Decimal' conform to 'BinaryInteger'
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x).isPowerOf(n)
}
func add(x: String, y: String) -> Int {
return Int(x) + Int(y)
}
func vowelCount(s: String) -> Int {
return s.count(.vowel)
}
func isPalindrome(s: String) -> Bool {
return s.isPalindrome()
}
func countString(s: String, sub: String) -> Int {
return s.count(sub)
}
func countStringIgnoreCase(s: String, sub: String) -> Int {
return s.countIgnoreCase(sub)
}
func countStringIgnoreCaseAndPunctuation(s: String, sub: String) -> Int {
return s.countIgnoreCaseAndPunctuation(sub)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x).isPowerOf(n)
}
// -----------------------------------------------------------------------------
// 11. Write a function that returns the sum of two numbers.
// The two numbers are passed in as strings.
// Example: add("123", "321") // returns 444
// -----------------------------------------------------------------------------
func add(x: String, y: String) -> Int {
return Int(x) + Int(y)
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns the number of
// vowels in the string.
// You should ignore case.
// The vowels are 'a', 'e', 'i', 'o', and 'u'.
// Example: vowelCount("Hello") // returns 2
// -----------------------------------------------------------------------------
func vowelCount(s: String) -> Int {
return s.count(.vowel)
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string
// is a palindrome and false otherwise.
// A palindrome is a word that is spelled the same forwards and backwards.
// Example: isPalindrome("racecar") // returns true
// -----------------------------------------------------------------------------
func isPalindrome(s: String) -> Bool {
return s.isPalindrome()
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns the number of times
// that string appears in the string.
// Example: countString("Hello", "l") // returns 2
// -----------------------------------------------------------------------------
func countString(s: String, sub: String) -> Int {
return s.count(sub)
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns the number of times
// that string appears in the string, ignoring case.
// Example: countStringIgnoreCase("Hello", "l") // returns 2
// -----------------------------------------------------------------------------
func countStringIgnoreCase(s: String, sub: String) -> Int {
return s.countIgnoreCase(sub)
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns the number of times
// that string appears in the string, ignoring case and punctuation.
// Example: countStringIgnoreCaseAndPunctuation("Hello, world!", "l") // returns 3
// -----------------------------------------------------------------------------
func countStringIgnoreCaseAndPunctuation(s: String, sub: String) -> Int {
return s.countIgnoreCaseAndPunctuation(sub)
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns the number of times
// that string appears in the string, ignoring case, punctuation, and spaces.
// Example: countStringIgnoreCaseAndPunctuationAndSpaces("Hello, world!", "l") // returns 3
// ---------------
return Int(x).isPowerOf(n) // value of type 'Int' has no member 'isPowerOf'
return Int(x) + Int(y) // binary operator '+' cannot be applied to two 'Int?' operands
return s.count(.vowel) // cannot infer contextual base in reference to member 'vowel'
return s.count(.vowel) // cannot call value of non-function type 'Int'
return s.isPalindrome() // value of type 'String' has no member 'isPalindrome'
return s.count(sub) // cannot call value of non-function type 'Int'
return s.countIgnoreCase(sub) // value of type 'String' has no member 'countIgnoreCase'
return s.countIgnoreCaseAndPunctuation(sub) // value of type 'String' has no member 'countIgnoreCaseAndPunctuation'
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(log(Double(x), n)))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(log(Double(x), n)))
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
return Int(x) == pow(n, Int(log(Double(x), n))) // operator function '==' requires that 'Decimal' conform to 'BinaryInteger'
return Int(x) == pow(n, Int(log(Double(x), n))) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return Int(x) == pow(n, Int(log(Double(x), n))) // extra argument in call
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if x % n != 0 {
return false
}
let result = x / n
if result == 1 {
return true
}
return isSimplePower(x: result, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if x % n != 0 {
return false
}
let result = x / n
if result == 1 {
return true
}
return isSimplePower(x: result, n: n)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if x % n != 0 {
return false
}
let pow = x / n
if pow == 1 {
return true
}
return isSimplePower(x: pow, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if x % n != 0 {
return false
}
let pow = x / n
if pow == 1 {
return true
}
return isSimplePower(x: pow, n: n)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(n) ** Int(n)
}
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(n) ** Int(n)
}
// -----------------------------------------------------------------------------
// 12. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 13. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 14. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 15. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 16. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 17. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 18. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) == 2
// numberOfDigits(1) == 1
// numberOfDigits(0) == 1
func numberOfDigits(number: Int) -> Int {
return String(number).count
}
// -----------------------------------------------------------------------------
// 19. Write a function that returns the number of digits of a given integer.
// For example:
// numberOfDigits(1234) == 4
// numberOfDigits(12) ==
return Int(x) == Int(n) ** Int(n) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(n) ** Int(n)
}
func add(a: Int, b: Int) -> Int {
return a + b
}
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(n) ** Int(n)
}
// -----------------------------------------------------------------------------
// 12. Write a function that returns the sum of two numbers.
// Example:
// add(1, 2) == 3
func add(a: Int, b: Int) -> Int {
return a + b
}
// -----------------------------------------------------------------------------
// 13. Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples:
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
// -----------------------------------------------------------------------------
// 14. Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples:
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
// -----------------------------------------------------------------------------
// 15. Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples:
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
// -----------------------------------------------------------------------------
// 16. Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples:
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
// -----------------------------------------------------------------------------
// 17. Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples:
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
func doubleChar(s: String) -> String {
return String(s).map { $0 * 2 }.joined()
}
// -----------------------------------------------------------------------------
// 18. Given a string, you have to return
return Int(x) == Int(n) ** Int(n) // no operator '**' is defined; did you mean 'pow(_:_:)'?
return String(s).map { $0 * 2 }.joined() // cannot convert value of type 'Int' to closure result type 'String'
return String(s).map { $0 * 2 }.joined() // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'Int'
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(x))
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
func removeVowels(string: String) -> String {
return string.filter { !isVowel($0) }
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(x))
}
// 12. Write a function that takes a string as an argument and returns the
// string with the letters reversed.
// For example:
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 13. Write a function that takes a string as an argument and returns true if
// the string is a palindrome and false if it is not.
// A palindrome is a word, phrase, number, or other sequence of characters
// which reads the same backward as forward, such as madam or racecar.
// For example:
// isPalindrome("madam") == true
// isPalindrome("hello") == false
// isPalindrome("123210") == false
// isPalindrome("12321") == true
// isPalindrome("12345") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
// 14. Write a function that takes a string as an argument and returns the
// string with all vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("aeiou") == ""
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
func removeVowels(string: String) -> String {
return string.filter { !isVowel($0) }
}
// 15. Write a function that takes a string as an argument and returns true if
// the string is a palindrome and false if it is not.
// A palindrome is a word, phrase, number, or other sequence of characters
// which reads the same backward as forward, such as madam or racecar.
// For example:
// isPalindrome("madam") == true
// isPalindrome("hello") == false
// isPalindrome("123210") == false
// isPalindrome("12321") == true
// isPalindrome("12345") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
// 16. Write a function that takes a string as an argument and returns true if
// the string is a palindrome and false if it is not.
// A palindrome is a word, phrase, number, or other sequence of characters
// which reads the same backward as forward, such as madam or racecar.
// For example:
// isPalindrome("madam") == true
// isPalindrome("hello") == false
// isPalindrome("123210") == false
// isPalindrome("12321") == true
// isPalindrome("12345") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed().join()
}
// 17. Write a function that takes a string as an argument and returns true if
// the string is a palindrome and false if it is not.
// A palindrome is a word, phrase, number, or other sequence of characters
// which reads the same backward as forward, such as madam or racecar.
// For example:
// isPalindrome("madam") == true
// isPalindrome("hello") == false
// isPalindrome("123210") == false
// isPalindrome("12321") == true
// isPalindrome("12345") == false
func isPalindrome(
return Int(x) == pow(n, Int(x)) // operator function '==' requires that 'Decimal' conform to 'BinaryInteger'
return Int(x) == pow(n, Int(x)) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string == string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return string.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(pow(n, Int(log2(x))))
}
func removeVowels(s: String) -> String {
return s.trim().filter { !isVowel($0) }
}
func removeConsonants(s: String) -> String {
return s.trim().filter { isConsonant($0) }
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == Int(pow(n, Int(log2(x))))
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdrbr"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
return s.trim().filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all
// the consonants removed.
// For example:
// removeConsonants("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdrbr"
// removeConsonants("") == ""
func removeConsonants(s: String) -> String {
return s.trim().filter { isConsonant($0) }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeConsonants("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdrbr"
// removeConsonants("") == ""
func removeConsonants(s: String) -> String {
return s.trim().filter { isConsonant($0) }
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeConsonants("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdrbr"
// removeConsonants("") == ""
func removeConsonants(s: String) -> String {
return s.trim().filter { isConsonant($0) }
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeConsonants("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") == "brcrdrbr"
// removeConsonants("") == ""
func removeConsonants(s: String) -> String {
return s.trim().filter { isConsonant($0) }
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeConsonants("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeConsonants("abracadabra") ==
return Int(x) == Int(pow(n, Int(log2(x)))) // no exact matches in call to global function 'log2'
return Int(x) == Int(pow(n, Int(log2(x)))) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return Int(x) == Int(pow(n, Int(log2(x)))) // initializer 'init(_:)' requires that 'Decimal' conform to 'BinaryInteger'
return s.trim().filter { !isVowel($0) } // value of type 'String' has no member 'trim'
return s.trim().filter { !isVowel($0) } // cannot find 'isVowel' in scope
return s.trim().filter { isConsonant($0) } // cannot find 'isConsonant' in scope
return s.trim().filter { isConsonant($0) } // value of type 'String' has no member 'trim'
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n)))
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n)))
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/546e2562b03326a88e000020/train/swift
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n))) // cannot convert value of type 'Int' to expected argument type 'Decimal'
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n))) // cannot convert value of type 'Int' to expected argument type 'Double'
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n))) // cannot convert value of type 'Int' to expected argument type 'Double'
return Int(x) == pow(n, Int(log(Double(x) / log(n)) / log(n))) // operator function '==' requires that 'Decimal' conform to 'BinaryInteger'
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
func sortString(s: String) -> String {
return String(sorted: s)
}
func countVowels(s: String) -> Int {
return s.count(where: \Character.isVowel)
}
func isPalindrome(s: String) -> Bool {
return s == String(sorted: s.reversed())
}
func removeVowels(s: String) -> String {
return s.replacingCharacters(with: "aeiouAEIOU", options: .caseInsensitive)
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns a string in which
// characters are sorted in alphabetical order.
// Examples:
// sortString("hello") == "ehllo"
// sortString("edabit") == "abdeit"
// sortString("hacker") == "aaeehh"
// sortString("geek") == "aeegk"
// sortString("javascript") == "aacijprstv"
func sortString(s: String) -> String {
return String(sorted: s)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns the number of
// vowels in the string.
// Note:
// The vowel letters are: a, e, i, o, u, and the letter y.
// The letter y should not be counted as a vowel if it is the first or
// last letter in the string.
// The function should be case-insensitive, meaning that A and a should
// be counted together.
// Examples:
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
func countVowels(s: String) -> Int {
return s.count(where: \Character.isVowel)
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns true if the string
// is a palindrome and false otherwise.
// Note:
// A palindrome is a word that is spelled the same forwards and backwards.
// Examples:
// isPalindrome("anna") == true
// isPalindrome("civic") == true
// isPalindrome("civic2") == false
// isPalindrome("apple") == false
func isPalindrome(s: String) -> Bool {
return s == String(sorted: s.reversed())
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with
// all vowels removed.
// Note:
// The vowel letters are: a, e, i, o, u, and the letter y.
// The letter y should not be counted as a vowel if it is the first or
// last letter in the string.
// The function should be case-insensitive, meaning that A and a should
// be counted together.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Coke."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " prtr"
// removeVowels("bring out your dead body") == " brng yt hw ydb"
func removeVowels(s: String) -> String {
return s.replacingCharacters(with: "aeiouAEIOU", options: .caseInsensitive)
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Note:
// The vowel letters are: a, e, i, o, u, and the letter y.
// The letter y should not be counted as a vowel if it is the first or
// last letter in the string.
// The function should be case-insensitive, meaning that A and a should
// be counted
return Int(cbrt(a)) ** 3 == a // no operator '**' is defined; did you mean 'pow(_:_:)'?
return Int(cbrt(a)) ** 3 == a // no exact matches in call to global function 'cbrt'
return String(sorted: s) // no exact matches in call to initializer
return s.count(where: \Character.isVowel) // cannot call value of non-function type 'Int'
return s.count(where: \Character.isVowel) // value of type 'Character' has no member 'isVowel'
return s == String(sorted: s.reversed()) // no exact matches in call to initializer
return s.replacingCharacters(with: "aeiouAEIOU", options: .caseInsensitive) // extra argument 'options' in call
return s.replacingCharacters(with: "aeiouAEIOU", options: .caseInsensitive) // missing argument for parameter 'in' in call
return s.replacingCharacters(with: "aeiouAEIOU", options: .caseInsensitive) // cannot infer contextual base in reference to member 'caseInsensitive'
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
func isPerfectPower(a: Int) -> Bool {
var root = Int(cbrt(Double(a)))
while root * root * root > a {
root -= 1
}
return root * root * root == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an integer a and returns true if it is a perfect
// power. A perfect power is defined as an integer that can be expressed as
// an integer power of another integer.
// Examples:
// isPerfectPower(4) == true
// isPerfectPower(5) == false
// isPerfectPower(16) == true
// isPerfectPower(100) == true
// isPerfectPower(99) == false
// isPerfectPower(6561) == true
// isPerfectPower(216) == true
// isPerfectPower(6560) == false
// isPerfectPower(1) == true
// isPerfectPower(2) == true
// isPerfectPower(81) == true
// isPerfectPower(1000000000000000) == false
func isPerfectPower(a: Int) -> Bool {
var root = Int(cbrt(Double(a)))
while root * root * root > a {
root -= 1
}
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an integer a and returns true if it is a perfect
// power. A perfect power is defined as an integer that can be expressed as
// an integer power of another integer.
// Examples:
// isPerfectPower(4) == true
// isPerfectPower(5) == false
// isPerfectPower(16) == true
// isPerfectPower(100) == true
// isPerfectPower(99) == false
// isPerfectPower(6561) == true
// isPerfectPower(216) == true
// isPerfectPower(6560) == false
// isPerfectPower(1) == true
// isPerfectPower(2) == true
// isPerfectPower(81) == true
// isPerfectPower(1000000000000000) == false
func isPerfectPower(a: Int) -> Bool {
var root = Int(cbrt(Double(a)))
while root * root * root > a {
root -= 1
}
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an integer a and returns true if it is a perfect
// power. A perfect power is defined as an integer that can be expressed as
// an integer power of another integer.
// Examples:
// isPerfectPower(4) == true
// isPerfectPower(5) == false
// isPerfectPower(16) == true
// isPerfectPower(100) == true
// isPerfectPower(99) == false
// isPerfectPower(6561) == true
// isPerfectPower(216) == true
// isPerfectPower(6560) == false
// isPerfectPower(1) == true
// isPerfectPower(2) == true
// isPerfectPower(81) == true
// isPerfectPower(1000000000000000) == false
func isPerfectPower(a: Int) -> Bool {
var root = Int(cbrt(Double(a)))
while root * root * root > a {
root -= 1
}
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an integer a and returns true if it is a perfect
// power. A perfect power is defined as an integer that can be expressed as
// an integer power of another integer.
// Examples:
// is
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 12. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 13. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 14. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 15. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 16. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 17. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let x = Int(sqrt(a))
return x * x * x == a
}
// 18. Write a function that takes an integer a and returns
let x = Int(sqrt(a)) // no exact matches in call to global function 'sqrt'
func iscube(a: Int) -> Bool {
let sqrt = Int(sqrt(Double(a)))
return sqrt * sqrt == a
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func removeNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result += char
}
}
return result
}
func reverseAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result = char + result
}
}
return result
}
func reverseAndRemoveNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result = char + result
}
}
return result
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let sqrt = Int(sqrt(Double(a)))
return sqrt * sqrt == a
}
// 2. Write a function that takes a string and returns a string
// with all vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("pear tree") == " pr t"
// removeVowels("ho ho ho") == "h h h"
// removeVowels("uwu uwu") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a string
// with all non-alphabetic characters removed.
// Examples:
// removeNonAlphabetic("aiuoe") == ""
// removeNonAlphabetic("aiuoea") == "a"
// removeNonAlphabetic("aiuoea!@#$%^&*()") == "a"
// removeNonAlphabetic("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// removeNonAlphabetic("") == ""
func removeNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a string
// with all alphabetic characters in reverse order.
// Examples:
// reverseAlphabetic("I have never seen a thin person drinking Diet Coke.") == ".kc d ni rt dahP esac siht nrev yrev a hvej I"
// reverseAlphabetic("abracadabra") == "arbadacarba"
// reverseAlphabetic("pear tree") == "eart tree"
// reverseAlphabetic("ho ho ho") == "ho ho ho"
// reverseAlphabetic("") == ""
func reverseAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result = char + result
}
}
return result
}
// 5. Write a function that takes a string and returns a string
// with all non-alphabetic characters removed and the remaining
// characters reversed.
// Examples:
// reverseAndRemoveNonAlphabetic("I have never seen a thin person drinking Diet Coke.") == ".kc d ni rt dahP esac siht nrev yrev a hvej I"
// reverseAndRemoveNonAlphabetic("abracadabra") == "arbadacarba"
// reverseAndRemoveNonAlphabetic("pear tree") == "eart tree"
// reverseAndRemoveNonAlphabetic("ho ho ho") == "ho ho ho"
// reverseAndRemoveNonAlphabetic("") == ""
func reverseAndRemoveNonAlphabetic(input: String) -> String {
var result = ""
for char in input {
if char.isAlphabetic() {
result = char + result
}
}
return result
}
// 6. Write a function that takes a string and returns a string
// with all alphabetic characters in reverse order and the remaining
// characters left unchanged.
// Examples:
// reverseAlphabeticAndRemoveNonAlphabetic("I have never seen a thin person drinking Diet Coke.") == ".kc d ni rt dahP esac siht
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isAlphabetic() { // value of type 'Character' has no member 'isAlphabetic'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isAlphabetic() { // value of type 'Character' has no member 'isAlphabetic'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
if char.isAlphabetic() { // value of type 'Character' has no member 'isAlphabetic'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes an integer a and returns true ...
// ... if it is a perfect cube. Otherwise return false.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an integer a and returns true ...
// ... if it is a perfect cube. Otherwise return false.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an integer a and returns true ...
// ... if it is a perfect cube. Otherwise return false.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an integer a and returns true ...
// ... if it is a perfect cube. Otherwise return false.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an integer a and returns true ...
// ... if it is a perfect cube. Otherwise return false.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a:
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
func countVowel(s: String) -> Int {
var count = 0
for c in s {
switch c {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
func reverse(s: String) -> String {
var reversed = ""
for c in s {
reversed = c + reversed
}
return reversed
}
func reverseWords(s: String) -> String {
var reversed = ""
var word = ""
for c in s {
if c == " " {
reversed = word + " " + reversed
word = ""
} else {
word = c + word
}
}
reversed = word + " " + reversed
return reversed
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of vowels
// in the string.
// Note: you may assume the string will always be valid.
// a, e, i, o, u are considered vowels (not y).
// The letters a, o, u, and i are not considered vowels.
// Examples:
// countVowel("ciao") == 2
// countVowel("abracadabra") == 5
// countVowel("abcdefghijklmnopqrstuvwxyz") == 5
func countVowel(s: String) -> Int {
var count = 0
for c in s {
switch c {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with
// the sentence in reversed order.
// Note: you may assume the input is always valid.
// Examples:
// reverse("Hello world!") == "!dlrow olleH"
// reverse("Hi There.") == ".eht RehtaH"
func reverse(s: String) -> String {
var reversed = ""
for c in s {
reversed = c + reversed
}
return reversed
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with
// the sentence in reversed order while keeping the word order.
// Note: you may assume the input is always valid.
// Examples:
// reverseWords("Hello world!") == "world! Hello"
// reverseWords("Hi There.") == "There. Hi"
func reverseWords(s: String) -> String {
var reversed = ""
var word = ""
for c in s {
if c == " " {
reversed = word + " " + reversed
word = ""
} else {
word = c + word
}
}
reversed = word + " " + reversed
return reversed
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with
// the sentence in reversed order while keeping the word order.
// Note: you may assume the input is always valid.
// Examples:
// reverseWords("Hello world!") == "world! Hello"
// reverseWords("Hi There.") == "There. Hi"
func reverseWords(s: String) -> String {
var reversed = ""
var word = ""
for c in s {
if c == " " {
reversed = word + " " + reversed
word = ""
} else {
word = c + word
}
}
reversed = word + " " + reversed
return reversed
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with
// the sentence in reversed order while keeping the word order.
// Note: you may assume the input is always valid.
// Examples:
// reverseWords("Hello world!") == "world! Hello"
// reverseWords("Hi There.") == "There. Hi"
func reverseWords(s: String) -> String {
var reversed = ""
var word = ""
for c in s {
if c == " " {
reversed = word + " " + reversed
word = "
return Int(cbrt(a)) ** 3 == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) ** 3 == a // no operator '**' is defined; did you mean 'pow(_:_:)'?
reversed = c + reversed // cannot convert value of type 'Character' to expected argument type 'String'
word = c + word // cannot convert value of type 'Character' to expected argument type 'String'
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
return Int(cbrt(a)) ** 3 == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) ** 3 == a // no operator '**' is defined; did you mean 'pow(_:_:)'?
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
func countVowels(s: String) -> Int {
var count = 0
for c in s {
switch c {
case "a":
case "e":
case "i":
case "o":
case "u":
count += 1
default:
break
}
}
return count
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) ** 3 == a
}
// 2. Write a function that takes a string and returns the number of
// vowels in the string.
// Note: you may assume the string is in lowercase.
// Examples:
// countVowels("apple") == 2
// countVowels("banana") == 3
// countVowels("grapefruit") == 5
// countVowels("kiwi") == 3
// countVowels("orange") == 5
// countVowels("pineapple") == 5
// countVowels("cherry") == 3
func countVowels(s: String) -> Int {
var count = 0
for c in s {
switch c {
case "a":
case "e":
case "i":
case "o":
case "u":
count += 1
default:
break
}
}
return count
}
// 3. Write a function that takes a string and returns the number of
// consonants in the string.
// Note: you may assume the string is in lowercase.
// Examples:
// countConsonants("apple") == 4
// countConsonants("banana") == 6
// countConsonants("grapefruit") == 7
// countConsonants("kiwi") == 4
// countConsonants("orange") == 5
// countConsonants("pineapple") == 5
// countConsonants("cherry") == 4
func countConsonants(s: String) -> Int {
var count = 0
for c in s {
switch c {
case "a":
case "e":
case "i":
case "o":
case "u":
case "y":
case "w":
case "h":
case "k":
case "l":
case "m":
case "n":
case "p":
case "q":
case "r":
case "s":
case "t":
case "v":
case "x":
case "z":
case "d":
case "f":
case "g":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
case "j":
return Int(cbrt(a)) ** 3 == a // no operator '**' is defined; did you mean 'pow(_:_:)'?
return Int(cbrt(a)) ** 3 == a // no exact matches in call to global function 'cbrt'
case "a": // 'case' label in a 'switch' must have at least one executable statement
case "e": // 'case' label in a 'switch' must have at least one executable statement
case "i": // 'case' label in a 'switch' must have at least one executable statement
case "o": // 'case' label in a 'switch' must have at least one executable statement
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let root = Int(cbrt(Double(a)))
return root * root * root == a
}
// -----------------------------------------------------------------------------
// 19. Write a function that takes an integer a and returns true ...
// ... if this integer is a perfect cube.
// Examples:
// iscube(a:
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
func ispower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
func isperfectcube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
func isperfectpower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
func isperfectsquare(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
func isperfectfifthpower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 2. Write a function that takes an integer a and returns true
// if this ingeger is a power of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// ispower(a: 1) == true
// ispower(a: 2) == false
// ispower(a: -1) == true
// ispower(a: 64) == true
// ispower(a: 0) == true
// ispower(a: 180) == false
func ispower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 3. Write a function that takes an integer a and returns true
// if this ingeger is a perfect cube.
// Note: you may assume the input is always valid.
// Examples:
// isperfectcube(a: 1) == true
// isperfectcube(a: 2) == false
// isperfectcube(a: -1) == true
// isperfectcube(a: 64) == true
// isperfectcube(a: 0) == true
// isperfectcube(a: 180) == false
func isperfectcube(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 4. Write a function that takes an integer a and returns true
// if this ingeger is a perfect power.
// Note: you may assume the input is always valid.
// Examples:
// isperfectpower(a: 1) == true
// isperfectpower(a: 2) == false
// isperfectpower(a: -1) == true
// isperfectpower(a: 64) == true
// isperfectpower(a: 0) == true
// isperfectpower(a: 180) == false
func isperfectpower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 5. Write a function that takes an integer a and returns true
// if this ingeger is a perfect square.
// Note: you may assume the input is always valid.
// Examples:
// isperfectsquare(a: 1) == true
// isperfectsquare(a: 2) == false
// isperfectsquare(a: -1) == true
// isperfectsquare(a: 64) == true
// isperfectsquare(a: 0) == true
// isperfectsquare(a: 180) == false
func isperfectsquare(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 6. Write a function that takes an integer a and returns true
// if this ingeger is a perfect fifth power.
// Note: you may assume the input is always valid.
// Examples:
// isperfectfifthpower(a: 1) == true
// isperfectfifthpower(a: 2) == false
// isperfectfifthpower(a: -1) == true
// isperfectfifthpower(a: 64) == true
// isperfectfifthpower(a: 0) == true
// isperfectfifthpower(a: 180) == false
func isperfectfifthpower(a: Int) -> Bool {
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a
}
// 7. Write a function that takes an integer a and returns true
// if this ingeger is a perfect fourth power.
// Note: you may assume the input is always valid.
// Examples:
// isperfectfourthpower(a: 1) == true
// isperfectfourthpower(a: 2) == false
// isperfectfourthpower(a: -1) == true
// isperfectfourthpower(a: 64) == true
// isperfectfourthpower(
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
return Int(cbrt(a)) * Int(cbrt(a)) * Int(cbrt(a)) == a // no exact matches in call to global function 'cbrt'
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var count = 0
for i in num {
if hex.contains(i) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var count = 0
for i in num {
if hex.contains(i) {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
if hex.contains(i) { // cannot convert value of type 'Character' to expected argument type 'String'
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
let count = 0
for i in num.uppercase {
if hex.contains(i) {
count += 1
}
}
return count
}
func sumNumbers(s: String) -> Int {
var sum = 0
for i in s {
if i.isNumber {
sum += i
}
}
return sum
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
let count = 0
for i in num.uppercase {
if hex.contains(i) {
count += 1
}
}
return count
}
// 2.
// Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more
// continuous digits (0-9).
// So the strings "abc123xyz" and "aa11b33" only return 123 and 33
// respectively.
// Note: ignore all non-numeric characters in the string.
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5one") == 5
// sumNumbers("1st42nd") == 42
// sumNumbers("") == 0
// sumNumbers("ab123") == 123
func sumNumbers(s: String) -> Int {
var sum = 0
for i in s {
if i.isNumber {
sum += i
}
}
return sum
}
// 3.
// Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more
// continuous digits (0-9).
// So the strings "abc123xyz" and "aa11b33" only return 123 and 33
// respectively.
// Note: ignore all non-numeric characters in the string.
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5one") == 5
// sumNumbers("1st42nd") == 42
// sumNumbers("") == 0
// sumNumbers("ab123") == 123
func sumNumbers(s: String) -> Int {
var sum = 0
for i in s {
if i.isNumber {
sum += i
}
}
return sum
}
// 4.
// Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more
// continuous digits (0-9).
// So the strings "abc123xyz" and "aa11b33" only return 123 and 33
// respectively.
// Note: ignore all non-numeric characters in the string.
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5one") == 5
// sumNumbers("1st42nd") == 42
// sumNumbers("") == 0
// sumNumbers("ab123") == 123
func sumNumbers(s: String) -> Int {
var sum = 0
for i in s {
if i.isNumber {
sum += i
}
}
return sum
}
// 5.
// Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more
// continuous digits (0-9).
for i in num.uppercase { // value of type 'String' has no member 'uppercase'
sum += i // cannot convert value of type 'Character' to expected argument type 'Int'
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var count = 0
for i in num {
if hex.contains(String(i)) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var count = 0
for i in num {
if hex.contains(String(i)) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" || char == "B" || char == "D" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if isPrime(Int(i)) {
count += 1
}
}
return count
}
func isPrime(num: Int) -> Bool {
if num == 2 {
return true
}
if num % 2 == 0 {
return false
}
for i in 3..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for i in num {
if isPrime(Int(i)) {
count += 1
}
}
return count
}
func isPrime(num: Int) -> Bool {
if num == 2 {
return true
}
if num % 2 == 0 {
return false
}
for i in 3..<num {
if num % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
if isPrime(Int(i)) { // missing argument label 'num:' in call
if isPrime(Int(i)) { // no exact matches in call to initializer
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
func hexKey(num: String) -> Int {
var count = 0
var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
for i in num {
if hex.contains(String(i)) {
count += 1
}
}
return count
}
func vowels(str: String) -> Int {
var count = 0
var vowels = ["a", "e", "i", "o", "u"]
for i in str {
if vowels.contains(String(i)) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
for i in num {
if hex.contains(String(i)) {
count += 1
}
}
return count
}
// 2.
// Write a function that receives a string and returns the number of vowels
// (a, e, i, o, u) in the string.
// Note: you may assume the input is always correct or empty string.
// Examples:
// vowels("apple") == 2
// vowels("banana") == 3
// vowels("") == 0
// vowels("xyz") == 0
func vowels(str: String) -> Int {
var count = 0
var vowels = ["a", "e", "i", "o", "u"]
for i in str {
if vowels.contains(String(i)) {
count += 1
}
}
return count
}
// 3.
// Write a function that receives a string and returns the number of words
// in the string.
// Note: you may assume the input is always correct or empty string.
// Examples:
// words("Hello world") == 2
// words("") == 0
// words("xyz") == 0
// words("Hello world!") == 2
// words("Hello world!!!") == 2
// words("Hello world!!!!!") == 2
// words("Hello world!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] // variable 'hex' was never mutated; consider changing to 'let' constant
var vowels = ["a", "e", "i", "o", "u"] // variable 'vowels' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
for char in num {
if char == "2" || char == "3" || char == "5" || char == "7" ||
char == "B" || char == "D" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
return binary.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
if decimal % 2 == 0 {
binary += "0"
} else {
binary += "1"
}
decimal /= 2
}
return binary
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
if decimal % 2 == 0 {
binary += "0"
} else {
binary += "1"
}
decimal /= 2
}
return binary
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
return binary.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
return "db" + binary + "db"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
return binary.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
binary += String(decimal % 2)
decimal /= 2
}
return binary.reversed().join()
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
return binary.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
if decimal % 2 == 0 {
binary += "0"
} else {
binary += "1"
}
decimal /= 2
}
return binary.reversed().join()
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = "db"
while decimal > 0 {
if decimal % 2 == 0 {
binary += "0"
} else {
binary += "1"
}
decimal /= 2
}
return binary.reversed().join()
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
return binary.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func isHappy(s: String) -> Bool {
if s.length < 3 {
return false
}
var count = 0
for i in 0..<s.length-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
count += 1
}
}
return count == 0
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.length < 3 {
return false
}
var count = 0
for i in 0..<s.length-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
count += 1
}
}
return count == 0
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 2:
// Write a function that takes a string and returns a string with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "") == ""
// reverse(s: "h") == "h"
// reverse(s: "a") == "a"
// reverse(s: "a b c") == "c b a"
// reverse(s: "a-b-c") == "c-b-a"
// reverse(s: "a-b-c-d") == "d-c-b-a"
// reverse(s: "a-b-c-d-e") == "e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f") == "f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g") == "g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h") == "h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i") == "i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j") == "j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k") == "k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l") == "l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l-m") == "m-l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l-m-n") == "n-m-l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o") == "o-n-m-l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p") == "p-o-n-m-l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q") == "q-p-o-n-m-l-k-j-i-h-g-f-e-d-c-b-a"
// reverse(s: "a-b-c-d-e-f-g-h-
if s.length < 3 { // value of type 'String' has no member 'length'
for i in 0..<s.length-2 { // value of type 'String' has no member 'length'
func isHappy(s: String) -> Bool {
var count = 0
var i = 0
while i < s.count {
if s[i] == s[i+1] || s[i] == s[i+2] {
count += 1
}
i += 1
}
return count == 0
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var count = 0
var i = 0
while i < s.count {
if s[i] == s[i+1] || s[i] == s[i+2] {
count += 1
}
i += 1
}
return count == 0
}
// Task
// Given a string, s, return the number of times that the string contains a substring that is a palindrome.
// A palindrome is a string that is the same forwards and backwards.
// For example:
// palindromeCount(s: "abba") == 2
// palindromeCount(s: "abbaa") == 3
// palindromeCount(s: "abbaabba") == 4
// palindromeCount(s: "abbaabbaa") == 5
// palindromeCount(s: "abbaabbaabba") == 6
// palindromeCount(s: "abbaabbaabbaa") == 7
// palindromeCount(s: "abbaabbaabbaabba") == 8
// palindromeCount(s: "abbaabbaabbaabbaa") == 9
// palindromeCount(s: "abbaabbaabbaabbaabba") == 10
// palindromeCount(s: "abbaabbaabbaabbaabbaa") == 11
// palindromeCount(s: "abbaabbaabbaabbaabbaabba") == 12
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaa") == 13
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabba") == 14
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaa") == 15
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabba") == 16
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaa") == 17
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabba") == 18
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 19
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 20
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 21
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 22
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 23
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 24
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 25
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 26
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 27
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 28
// palindromeCount(s: "abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaa") == 29
// palindromeCount(s: "abbaabbaabbaabbaabba
if s[i] == s[i+1] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
var seen = Set<String>()
while s.count > 0 {
if seen.contains(s) {
return false
}
seen.insert(s)
var sum = 0
for c in s {
sum += c.asciiRepresentation!.first!.numericValue!
}
s = String(characters: Character(UnicodeScalar(sum)), count: 1)
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
var seen = Set<String>()
while s.count > 0 {
if seen.contains(s) {
return false
}
seen.insert(s)
var sum = 0
for c in s {
sum += c.asciiRepresentation!.first!.numericValue!
}
s = String(characters: Character(UnicodeScalar(sum)), count: 1)
}
return true
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// For example:
// countVowels("Hello") == 2
// countVowels("apple") == 2
// countVowels("banana") == 3
// countVowels("") == 0
// countVowels("xyz") == 0
// countVowels("aeiou") == 5
// countVowels("AEIOU") == 5
// countVowels("AaEeIiOoUu") == 10
// countVowels("AaEeIiOoUu1234567890") == 10
// countVowels("AaEeIiOoUu1234567890aeiouAEIOU") == 15
// countVowels("AaEeIiOoUu1234567890aeiouAEIOUaAeEiIoOuU") == 20
// countVowels("AaEeIiOoUu1234567890aeiouAEIOUaAeEiIoOuUaAeEiIoOuU") == 30
// countVowels("AaEeIiOoUu1234567890aeiouAEIOUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuU") == 40
// countVowels("AaEeIiOoUu1234567890aeiouAEIOUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUaAeEiIoOuUa
sum += c.asciiRepresentation!.first!.numericValue! // value of type 'Character' has no member 'asciiRepresentation'
s = String(characters: Character(UnicodeScalar(sum)), count: 1) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
s = String(characters: Character(UnicodeScalar(sum)), count: 1) // incorrect argument label in call (have 'characters:count:', expected 'repeating:count:')
s = String(characters: Character(UnicodeScalar(sum)), count: 1) // cannot assign to value: 's' is a 'let' constant
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// For example:
// countVowels(s: "Hello") == 2
// countVowels(s: "apple") == 2
// countVowels(s: "banana") == 3
// countVowels(s: "") == 0
// countVowels(s: "a") == 1
// countVowels(s: "A") == 1
// countVowels(s: "Aa") == 1
// countVowels(s: "AaBb") == 2
// countVowels(s: "AaBbCc") == 3
// countVowels(s: "AaBbCcDd") == 4
// countVowels(s: "AaBbCcDdEe") == 5
// countVowels(s: "AaBbCcDdEeFf") == 6
// countVowels(s: "AaBbCcDdEeFfGg") == 7
// countVowels(s: "AaBbCcDdEeFfGgHh") == 8
// countVowels(s: "AaBbCcDdEeFfGgHhIi") == 9
// countVowels(s: "AaBbCcDdEeFfGgHhIiJj") == 10
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKk") == 11
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLl") == 12
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMm") == 13
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNn") == 14
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOo") == 15
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp") == 16
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQq") == 17
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRr") == 18
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSs") == 19
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTt") == 20
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtTu") == 21
// countVowels(s: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqR
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count - 2 {
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] {
return false
}
}
return true
}
func isPalindrome(s: String) -> Bool {
if s.count == 1 {
return true
}
for i in 0..<s.count / 2 {
if s[i] != s[s.count - i - 1] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count - 2 {
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] {
return false
}
}
return true
}
// Task 2
// You are given a string s.
// Your task is to check if the string is a palindrome.
// A string is a palindrome if it reads the same backward as forward.
// For example:
// isPalindrome(s: "a") == true
// isPalindrome(s: "ab") == false
// isPalindrome(s: "aba") == true
// isPalindrome(s: "abba") == true
// isPalindrome(s: "abbc") == false
// isPalindrome(s: "abcc") == false
// isPalindrome(s: "abcba") == true
// isPalindrome(s: "abcdba") == true
// isPalindrome(s: "abcdbac") == false
func isPalindrome(s: String) -> Bool {
if s.count == 1 {
return true
}
for i in 0..<s.count / 2 {
if s[i] != s[s.count - i - 1] {
return false
}
}
return true
}
// Task 3
// You are given a string s.
// Your task is to check if the string is a pangram.
// A pangram is a sentence that contains every letter in the English alphabet at least once.
// For example:
// isPangram(s: "a") == false
// isPangram(s: "ab") == false
// isPangram(s: "abc") == false
// isPangram(s: "abcdefghijklmnopqrstuvwxyz") == true
// isPangram(s: "The quick brown fox jumps over the lazy dog") == true
// isPangram(s: "The quick brown fox jumps over the lazy dog.") == true
// isPangram(s: "The quick brown fox jumps over the lazy dog!") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog,") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. .") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . .") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . .") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . . .") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog. . . . . ") == false
// isPangram(s: "The quick brown fox jumps over the lazy dog.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] || s[i] == s[i + 2] || s[i + 1] == s[i + 2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != s[s.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != s[s.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
import Foundation
class Solution {
var maxDepth = 0
func maxDepth(root: TreeNode?) -> Int {
if root == nil {
return 0
}
maxDepth(root: root.left)
maxDepth(root: root.right)
maxDepth += 1
return maxDepth
}
}
class Solution {
func maxDepth(root: TreeNode?) -> Int {
if root == nil {
return 0
}
var stack = [root]
var depth = 0
while stack.count > 0 {
var tempStack = []
for node in stack {
if node.left != nil {
tempStack.append(node.left)
}
if node.right != nil {
tempStack.append(node.right)
}
}
stack = tempStack
depth += 1
}
return depth
}
}
class Solution {
var result = []
func levelOrder(root: TreeNode?) {
if root == nil {
return
}
result.append(root.val)
levelOrder(root: root.left)
levelOrder(root: root.right)
}
}
class Solution {
func levelOrder(root: TreeNode?) -> [Int] {
if root == nil {
return []
}
var result = []
var queue = [root]
while queue.count > 0 {
var tempQueue = []
var tempResult = []
for node in queue {
tempResult.append(node.val)
if node.left != nil {
tempQueue.append(node.left)
}
if node.right != nil {
tempQueue.append(node.right)
}
}
result.append(tempResult)
queue = tempQueue
}
return result
}
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
var result = isHappy("aabb")
print(result)<|endoftext|>//
// main.swift
// 101-二叉树的最大深度
//
// Created by 邱翔宇 on 2019/1/29.
// Copyright © 2019 邱翔宇. All rights reserved.
//
import Foundation
// 给定一个二叉树,找出其最大深度。
// 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
// 说明: 叶子节点是指没有子节点的节点。
// 示例:
// 给定二叉树 [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// 返回它的最大深度 3 。
// 递归
class Solution {
var maxDepth = 0
func maxDepth(root: TreeNode?) -> Int {
if root == nil {
return 0
}
maxDepth(root: root.left)
maxDepth(root: root.right)
maxDepth += 1
return maxDepth
}
}
// 迭代
class Solution {
func maxDepth(root: TreeNode?) -> Int {
if root == nil {
return 0
}
var stack = [root]
var depth = 0
while stack.count > 0 {
var tempStack = []
for node in stack {
if node.left != nil {
tempStack.append(node.left)
}
if node.right != nil {
tempStack.append(node.right)
}
}
stack = tempStack
depth += 1
}
return depth
}
}<|endoftext|>//
// main.swift
// 102-二叉树的层次遍历
//
// Created by 邱翔宇 on 2019/1/29.
// Copyright © 2019 邱翔宇. All rights reserved.
//
import Foundation
// 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
// 例如:
// 给定二叉树: [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// 返回其层次遍历结果:
// [
// [3],
// [9,20],
// [15,7]
// ]
// 递归
class Solution {
var result = []
func levelOrder(root: TreeNode?) {
if root == nil {
return
}
result.append(root.val)
levelOrder(root: root.left)
levelOrder(root: root.right)
}
}
// 迭代
class Solution {
func levelOrder(root: TreeNode?) -> [Int] {
if root == nil {
return []
}
var result = []
var queue = [root]
while queue.count > 0 {
var tempQueue = []
var tempResult = []
for node in queue {
tempResult.append(node.val)
if node.left != nil {
tempQueue.append(node.left)
}
if node.right != nil {
tempQueue.append(node.right)
}
}
result.append(tempResult)
queue = tempQueue
}
return result
}
}<
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func maxDepth(root: TreeNode?) -> Int { // cannot find type 'TreeNode' in scope
maxDepth(root: root.left) // cannot call value of non-function type 'Int'
maxDepth(root: root.right) // cannot call value of non-function type 'Int'
class Solution { // invalid redeclaration of 'Solution'
func maxDepth(root: TreeNode?) -> Int { // cannot find type 'TreeNode' in scope
var tempStack = [] // empty collection literal requires an explicit type
class Solution { // invalid redeclaration of 'Solution'
var result = [] // empty collection literal requires an explicit type
func levelOrder(root: TreeNode?) { // cannot find type 'TreeNode' in scope
class Solution { // invalid redeclaration of 'Solution'
func levelOrder(root: TreeNode?) -> [Int] { // cannot find type 'TreeNode' in scope
var result = [] // empty collection literal requires an explicit type
var tempQueue = [] // empty collection literal requires an explicit type
var tempResult = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
// Task
// Given a string, find the length of the longest substring without repeating characters.
// Example 1:
// Input: "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
// Solution
// 1. Use a set to store the characters
// 2. Use two pointers to keep track of the start and end of the substring
// 3. Use a variable to keep track of the length of the longest substring
// 4. Use a loop to iterate through the string
// 5. Use a loop to iterate through the substring
// 6. Use a loop to iterate through the characters
// 7. Use a loop to iterate through the characters
// 8. Use a loop to iterate through the characters
// 9. Use a loop to iterate through the characters
// 10. Use a loop to iterate through the characters
// 11. Use a loop to iterate through the characters
// 12. Use a loop to iterate through the characters
// 13. Use a loop to iterate through the characters
// 14. Use a loop to iterate through the characters
// 15. Use a loop to iterate through the characters
// 16. Use a loop to iterate through the characters
// 17. Use a loop to iterate through the characters
// 18. Use a loop to iterate through the characters
// 19. Use a loop to iterate through the characters
// 20. Use a loop to iterate through the characters
// 21. Use a loop to iterate through the characters
// 22. Use a loop to iterate through the characters
// 23. Use a loop to iterate through the characters
// 24. Use a loop to iterate through the characters
// 25. Use a loop to iterate through the characters
// 26. Use a loop to iterate through the characters
// 27. Use a loop to iterate through the characters
// 28. Use a loop to iterate through the characters
// 29. Use a loop to iterate through the characters
// 30. Use a loop to iterate through the characters
// 31. Use a loop to iterate through the characters
// 32. Use a loop to iterate through the characters
// 33. Use a loop to iterate through the characters
// 34. Use a loop to iterate through the characters
// 35. Use a loop to iterate through the characters
// 36. Use a loop to iterate through the characters
// 37. Use a loop to iterate through the characters
// 38. Use a loop to iterate through the characters
// 39. Use a loop to iterate through the characters
// 40. Use a loop to iterate through the characters
// 41. Use a loop to iterate through the characters
// 42. Use a loop to iterate through the characters
// 43. Use a loop to iterate through the characters
// 44. Use a loop to iterate through the characters
// 45. Use a loop to iterate through the characters
// 46. Use a loop to iterate through the characters
// 47. Use a loop to iterate through the characters
// 48. Use a loop to iterate through the characters
// 49. Use a loop to iterate through the characters
// 50. Use a loop to iterate through the characters
// 51. Use a loop to iterate through the characters
// 52. Use a loop to iterate through the characters
// 53. Use a loop to iterate through the characters
// 54. Use a loop to iterate through the characters
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// Task 11
// ----------------------------------------------------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// Solution
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------------------------------
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
func firstRepeatedCharacter(s: String) -> String? {
var dictionary = [Character: Int]()
for character in s {
if dictionary[character] == nil {
dictionary[character] = 1
} else {
dictionary[character] += 1
}
}
for (character, count) in dictionary {
if count > 1 {
return String(character)
}
}
return nil
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
if s.count < 3 {
return false
}
for i in 0..<s.count-2 {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
// Task
// Given a string, find the first character that repeats and return it.
// If there are no repeating characters, return nil/None.
// Examples
// "aabbcde" --> "b"
// "abcdefgh" --> nil/None
// "aabBcde" --> "b"
// "aabBcdeB" --> "B"
// "aabBcdeBc" --> "B"
// "aabBcdeBcFf" --> "F"
// "" --> nil/None
// Solution
// 1. Create an empty dictionary to store the characters and their counts
// 2. Iterate through the string and update the count of each character in the dictionary
// 3. Iterate through the dictionary and find the first character with a count greater than 1
// 4. If no such character is found, return nil/None
// 5. Otherwise, return the character
// Time Complexity: O(n)
// Space Complexity: O(n)
func firstRepeatedCharacter(s: String) -> String? {
var dictionary = [Character: Int]()
for character in s {
if dictionary[character] == nil {
dictionary[character] = 1
} else {
dictionary[character] += 1
}
}
for (character, count) in dictionary {
if count > 1 {
return String(character)
}
}
return nil
}
// Task
// Given a string, find the first character that repeats and return it.
// If there are no repeating characters, return nil/None.
// Examples
// "aabbcde" --> "b"
// "abcdefgh" --> nil/None
// "aabBcde" --> "b"
// "aabBcdeB" --> "B"
// "aabBcdeBc" --> "B"
// "aabBcdeBcFf" --> "F"
// "" --> nil/None
// Solution
// 1. Create an empty dictionary to store the characters and their counts
// 2. Iterate through the string and update the count of each character in the dictionary
// 3. Iterate through the dictionary and find the first character with a count greater than 1
// 4. If no such character is found, return nil/None
// 5. Otherwise, return the character
// Time Complexity: O(n)
// Space Complexity: O(n)
func firstRepeatedCharacter(s: String) -> String? {
var dictionary = [Character: Int]()
for character in s {
if dictionary[character] == nil {
dictionary[character] = 1
} else {
dictionary[character] += 1
}
}
for (character, count) in dictionary {
if count > 1 {
return String(character)
}
}
return nil
}
// Task
// Given a string, find the first character that repeats and return it.
// If there are no repeating characters, return nil/None.
// Examples
// "aabbcde" --> "b"
// "abcdefgh" --> nil/None
// "aabBcde" --> "b"
// "aabBcdeB" --> "B"
// "aabBcdeBc" --> "B"
// "aabBcdeBcFf" --> "F"
// "" --> nil/None
// Solution
// 1. Create an empty dictionary to store the characters and their counts
// 2. Iterate through the string and update the count of each character in the dictionary
// 3. Iterate through the dictionary and find the first character with a count greater than 1
// 4. If no
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
dictionary[character] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.0...3.9:
result.append("B+")
case 2.0...2.9:
result.append("B")
case 1.0...1.9:
result.append("C+")
case 0.0...0.9:
result.append("C")
default:
result.append("D")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
switch grade {
case 4.0:
result.append("A+")
case 3.0...3.9:
result.append("B+")
case 2.0...2.9:
result.append("B")
case 1.0...1.9:
result.append("C+")
case 0.0...0.9:
result.append("C")
default:
result.append("D")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else {
result.append("E")
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
return Int(string.length) % 2 != 0
}
func countA(string: String) -> Int {
return string.count(for: "a")
}
func countA(string: String) -> Int {
return string.count(for: "a", options: .caseInsensitive)
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length) % 2 != 0
}
// 2. Write a function that takes a string and returns the number of times
// the letter "a" appears in it.
// Examples
// countA(string: "Hello") == 1
// countA(string: "Hello, World") == 2
// countA(string: "apple") == 1
// countA(string: "orange") == 0
func countA(string: String) -> Int {
return string.count(for: "a")
}
// 3. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, ignoring case.
// Examples
// countA(string: "Hello") == 1
// countA(string: "Hello, World") == 2
// countA(string: "apple") == 1
// countA(string: "orange") == 0
// countA(string: "A") == 1
// countA(string: "a") == 1
func countA(string: String) -> Int {
return string.count(for: "a", options: .caseInsensitive)
}
// 4. Write a function that takes a string and returns the number of times
// the letter "a" appears in it, ignoring case and punctuation.
// Examples
// countA(string: "Hello") == 1
// countA(string: "Hello, World") == 2
// countA(string: "apple") == 1
// countA(string: "orange") == 0
// countA(string: "A") == 1
// countA(string: "a") == 1
// countA(string: "Hello, apple!") == 1
// countA(string: "Hello, apple?") == 1
// countA(string: "Hello, apple!?") == 1
// countA(string: "Hello, apple!?!") == 1
// countA(string: "Hello, apple!?!?") == 1
// countA(string: "Hello, apple!?!?!") == 1
// countA(string: "Hello, apple!?!?!?") == 1
// countA(string: "Hello, apple!?!?!?!") == 1
// countA(string: "Hello, apple!?!?!?!?") == 1
// countA(string: "Hello, apple!?!?!?!??") == 1
// countA(string: "Hello, apple!?!?!?!???") == 1
// countA(string: "Hello, apple!?!?!?!????") == 1
// countA(string: "Hello, apple!?!?!?!?????") == 1
// countA(string: "Hello, apple!?!?!?!??????") == 1
// countA(string: "Hello, apple!?!?!?!???????") == 1
// countA(string: "Hello, apple!?!?!?!????????") == 1
// countA(string: "Hello, apple!?!?!?!?????????") == 1
// countA(string: "Hello, apple!?!?!?!??????????") == 1
// countA(string: "Hello, apple!?!?!?!???????????") == 1
// countA(string: "Hello, apple!?!?!?!????????????") == 1
// countA(string: "Hello, apple!?!?!?!?????????????") == 1
// countA(string: "Hello, apple!?!?!?!??????????????") == 1
// countA(string: "Hello, apple!?!?!?!???
return Int(string.length) % 2 != 0 // value of type 'String' has no member 'length'
return string.count(for: "a") // cannot call value of non-function type 'Int'
func countA(string: String) -> Int { // invalid redeclaration of 'countA(string:)'
return string.count(for: "a", options: .caseInsensitive) // cannot call value of non-function type 'Int'
return string.count(for: "a", options: .caseInsensitive) // cannot infer contextual base in reference to member 'caseInsensitive'
func primeLength(string: String) -> Bool {
return string.length % 2 == 1
}
func uniqueCharacters(string: String) -> Bool {
return string.count == Set(string).count
}
func firstNonRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) == 1 {
return String(char)
}
}
return nil
}
func firstRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) > 1 {
return String(char)
}
}
return nil
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return string.length % 2 == 1
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns true if the string
// contains only unique characters or false otherwise
// Examples
// uniqueCharacters(string: "Hello") == true
// uniqueCharacters(string: "abcdcba") == false
// uniqueCharacters(string: "kittens") == false
// uniqueCharacters(string: "orange") == true
func uniqueCharacters(string: String) -> Bool {
return string.count == Set(string).count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the first non-repeated
// character in the string. If there are no non-repeated characters, return nil.
// Examples
// firstNonRepeatedCharacter(string: "Hello") == "e"
// firstNonRepeatedCharacter(string: "abcdcba") == "a"
// firstNonRepeatedCharacter(string: "kittens") == "i"
// firstNonRepeatedCharacter(string: "orange") == "o"
func firstNonRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) == 1 {
return String(char)
}
}
return nil
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the first repeated
// character in the string. If there are no repeated characters, return nil.
// Examples
// firstRepeatedCharacter(string: "Hello") == "e"
// firstRepeatedCharacter(string: "abcdcba") == "d"
// firstRepeatedCharacter(string: "kittens") == "i"
// firstRepeatedCharacter(string: "orange") == "o"
func firstRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) > 1 {
return String(char)
}
}
return nil
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the first repeated
// character in the string. If there are no repeated characters, return nil.
// Examples
// firstRepeatedCharacter(string: "Hello") == "e"
// firstRepeatedCharacter(string: "abcdcba") == "d"
// firstRepeatedCharacter(string: "kittens") == "i"
// firstRepeatedCharacter(string: "orange") == "o"
func firstRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) > 1 {
return String(char)
}
}
return nil
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the first repeated
// character in the string. If there are no repeated characters, return nil.
// Examples
// firstRepeatedCharacter(string: "Hello") == "e"
// firstRepeatedCharacter(string: "abcdcba") == "d"
// firstRepeatedCharacter(string: "kittens") == "i"
// firstRepeatedCharacter(string: "orange") == "o"
func firstRepeatedCharacter(string: String) -> String? {
for char in string {
if string.count(char) > 1 {
return String(char)
}
}
return nil
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns the first repeated
// character in the string. If there are no repeated characters, return nil.
// Examples
// firstRepeatedCharacter(string: "Hello") == "e
return string.length % 2 == 1 // value of type 'String' has no member 'length'
if string.count(char) == 1 { // cannot call value of non-function type 'Int'
if string.count(char) > 1 { // cannot call value of non-function type 'Int'
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns the number of vowels
// in the string.
// Examples
// vowels(string: "apple") == 2
// vowels(string: "banana") == 3
// vowels(string: "kiwi") == 0
// vowels(string: "mango") == 3
// vowels(string: "orange") == 4
// vowels(string: "strawberry") == 6
// vowels(string: "watermelon") == 8
// vowels(string: "peach") == 2
// vowels(string: "pear") == 1
// vowels(string: "blueberry") == 5
// vowels(string: "raspberry") == 4
// vowels(string: "cinnamon") == 5
// vowels(string: "lemon") == 2
// vowels(string: "grapefruit") == 5
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi") == 0
// vowels(string: "kiwi
return Int(string.length).isPrime // value of type 'String' has no member 'length'
return Int(string.length).isPrime // reference to member 'isPrime' cannot be resolved without a contextual type
func primeLength(string: String) -> Bool {
return Int(string.length) % 2 == 1
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length) % 2 == 1
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of times
// the letter "a" appears in it.
// Examples
// countA(string: "Hello") == 1
// countA(string: "Hello, World!") == 2
// countA(string: "apple") == 1
// countA(string: "banana") == 3
// countA(string: "orange") == 1
// countA(string: "kiwi") == 0
// countA(string: "") == 0
// countA(string: "A") == 1
// countA(string: "a") == 1
// countA(string: "aa") == 2
// countA(string: "aaa") == 3
// countA(string: "aaaa") == 4
// countA(string: "aaaaa") == 5
// countA(string: "aaaaaa") == 6
// countA(string: "aaaaaaa") == 7
// countA(string: "aaaaaaaa") == 8
// countA(string: "aaaaaaaaa") == 9
// countA(string: "aaaaaaaaaa") == 10
// countA(string: "aaaaaaaaaaa") == 11
// countA(string: "aaaaaaaaaaaa") == 12
// countA(string: "aaaaaaaaaaaaa") == 13
// countA(string: "aaaaaaaaaaaaaa") == 14
// countA(string: "aaaaaaaaaaaaaaa") == 15
// countA(string: "aaaaaaaaaaaaaaaa") == 16
// countA(string: "aaaaaaaaaaaaaaaaa") == 17
// countA(string: "aaaaaaaaaaaaaaaaaa") == 18
// countA(string: "aaaaaaaaaaaaaaaaaaa") == 19
// countA(string: "aaaaaaaaaaaaaaaaaaaa") == 20
// countA(string: "aaaaaaaaaaaaaaaaaaaaa") == 21
// countA(string: "aaaaaaaaaaaaaaaaaaaaaa") == 22
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaa") == 23
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaa") == 24
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaa") == 25
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaa") == 26
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaa") == 27
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 28
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 29
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 30
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 31
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 32
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 33
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 34
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 35
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 36
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 37
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 38
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 39
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 40
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 41
// countA(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 42
// countA(string: "
return Int(string.length) % 2 == 1 // value of type 'String' has no member 'length'
func primeLength(string: String) -> Bool {
return string.length % 2 == 1
}
func containsVowel(string: String) -> Bool {
return string.contains("aeiou")
}
func containsOnlyLetters(string: String) -> Bool {
return string.isLetter
}
func containsOnlyLettersAndNumbers(string: String) -> Bool {
return string.isLetterOrNumber
}
func containsOnlyLettersNumbersAndSpaces(string: String) -> Bool {
return string.isLetterOrNumberOrSpace
}
func containsOnlyLettersNumbersAndSpaces(string: String) -> Bool {
return string.isLetterOrNumberOrSpaceOrSpace
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return string.length % 2 == 1
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns true if the string
// contains at least one vowel or false otherwise
// Examples
// containsVowel(string: "Hello") == true
// containsVowel(string: "abcdcba") == true
// containsVowel(string: "kittens") == true
// containsVowel(string: "orange") == false
func containsVowel(string: String) -> Bool {
return string.contains("aeiou")
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns true if the string
// contains only letters or false otherwise
// Examples
// containsOnlyLetters(string: "Hello") == true
// containsOnlyLetters(string: "abcdcba") == true
// containsOnlyLetters(string: "kittens") == true
// containsOnlyLetters(string: "orange") == false
func containsOnlyLetters(string: String) -> Bool {
return string.isLetter
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns true if the string
// contains only letters and numbers or false otherwise
// Examples
// containsOnlyLettersAndNumbers(string: "Hello") == true
// containsOnlyLettersAndNumbers(string: "abcdcba") == true
// containsOnlyLettersAndNumbers(string: "kittens") == true
// containsOnlyLettersAndNumbers(string: "orange") == false
func containsOnlyLettersAndNumbers(string: String) -> Bool {
return string.isLetterOrNumber
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns true if the string
// contains only letters, numbers, and spaces or false otherwise
// Examples
// containsOnlyLettersNumbersAndSpaces(string: "Hello") == true
// containsOnlyLettersNumbersAndSpaces(string: "abcdcba") == true
// containsOnlyLettersNumbersAndSpaces(string: "kittens") == true
// containsOnlyLettersNumbersAndSpaces(string: "orange") == false
func containsOnlyLettersNumbersAndSpaces(string: String) -> Bool {
return string.isLetterOrNumberOrSpace
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns true if the string
// contains only letters, numbers, and spaces, or numbers and spaces or false otherwise
// Examples
// containsOnlyLettersNumbersAndSpaces(string: "Hello") == true
// containsOnlyLettersNumbersAndSpaces(string: "abcdcba") == true
// containsOnlyLettersNumbersAndSpaces(string: "kittens") == true
// containsOnlyLettersNumbersAndSpaces(string: "orange") == false
func containsOnlyLettersNumbersAndSpaces(string: String) -> Bool {
return string.isLetterOrNumberOrSpaceOrSpace
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string and returns true if the string
// contains only letters, numbers, and spaces, or numbers and spaces, or
// numbers and spaces and numbers or false otherwise
// Examples
// containsOnlyLettersNumbersAndSpaces(string: "Hello") == true
// containsOnlyLettersNumbersAndSpaces(string: "abcdcba") == true
// containsOnlyLettersNumbersAndSpaces(string: "kittens") == true
// containsOnlyLettersNumbersAndSpaces(string: "orange") == false
func containsOnlyLettersNumbersAndSpaces(
return string.length % 2 == 1 // value of type 'String' has no member 'length'
return string.isLetter // value of type 'String' has no member 'isLetter'
return string.isLetterOrNumber // value of type 'String' has no member 'isLetterOrNumber'
return string.isLetterOrNumberOrSpace // value of type 'String' has no member 'isLetterOrNumberOrSpace'
func containsOnlyLettersNumbersAndSpaces(string: String) -> Bool { // invalid redeclaration of 'containsOnlyLettersNumbersAndSpaces(string:)'
return string.isLetterOrNumberOrSpaceOrSpace // value of type 'String' has no member 'isLetterOrNumberOrSpaceOrSpace'
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime() // value of type 'String' has no member 'length'
return Int(string.length).isPrime() // reference to member 'isPrime' cannot be resolved without a contextual type
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.10
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.11
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.12
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.13
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.14
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.15
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime
}
// -----------------------------------------------------------------------------
// 1.1.16
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
return Int(string.length).isPrime // value of type 'String' has no member 'length'
return Int(string.length).isPrime // reference to member 'isPrime' cannot be resolved without a contextual type
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime()
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
return Int(string.length).isPrime() // value of type 'String' has no member 'length'
return Int(string.length).isPrime() // reference to member 'isPrime' cannot be resolved without a contextual type
func primeLength(string: String) -> Bool {
if string.count % 2 == 0 {
return false
}
for i in 3...Int(sqrt(string.count)) {
if string.count % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
if string.count % 2 == 0 {
return false
}
for i in 3...Int(sqrt(string.count)) {
if string.count % i == 0 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
for i in 3...Int(sqrt(string.count)) { // no exact matches in call to global function 'sqrt'
func primeLength(string: String) -> Bool {
if string.count == 1 {
return true
}
for i in 2...(string.count / 2) {
if string.count % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
if string.count == 1 {
return true
}
for i in 2...(string.count / 2) {
if string.count % i == 0 {
return false
}
}
return true
}
// 2. Write a function that takes a string and returns the first character
// that is not repeated anywhere in the string.
// Examples
// firstNonRepeatedCharacter(string: "abcdcaf") == "b"
// firstNonRepeatedCharacter(string: "abcd") == "a"
// firstNonRepeatedCharacter(string: "aabbcc") == "c"
// firstNonRepeatedCharacter(string: "aabbc") == "d"
// firstNonRepeatedCharacter(string: "aabbcde") == "e"
// firstNonRepeatedCharacter(string: "aabbcdef") == "f"
// firstNonRepeatedCharacter(string: "aabbcdefg") == "g"
// firstNonRepeatedCharacter(string: "aabbcdefgh") == "h"
// firstNonRepeatedCharacter(string: "aabbcdefghi") == "i"
// firstNonRepeatedCharacter(string: "aabbcdefghij") == "j"
// firstNonRepeatedCharacter(string: "aabbcdefghijk") == "k"
// firstNonRepeatedCharacter(string: "aabbcdefghijkl") == "l"
// firstNonRepeatedCharacter(string: "aabbcdefghijklm") == "m"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmn") == "n"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmno") == "o"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoq") == "q"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqr") == "r"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrs") == "s"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsx") == "x"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxt") == "t"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxty") == "y"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyz") == "z"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzw") == "w"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwv") == "v"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvu") == "u"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvut") == "t"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvuti") == "i"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutin") == "n"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutinm") == "m"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutinmz") == "z"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutinmzp") == "p"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutinmzpq") == "q"
// firstNonRepeatedCharacter(string: "aabbcdefghijklmnoqrsxtyzwvutinmzpqr") == "r"
// firstNonRepeatedCharacter(string: "aabbcdef
// Fatal error: Range requires lowerBound <= upperBound
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
if i.isOneDigit() {
count += 1
}
}
return count
}
func divisibleBy11(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 {
count += 1
}
}
return count
}
func divisibleBy13(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 13 == 0 {
count += 1
}
}
return count
}
func divisibleBy17(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 17 == 0 {
count += 1
}
}
return count
}
func divisibleBy19(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 19 == 0 {
count += 1
}
}
return count
}
func divisibleBy23(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 23 == 0 {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
if i.isOneDigit() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.2.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleBy11(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.3.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleBy13(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 13 == 0 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.4.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBy17(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 17 == 0 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.5.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleBy19(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 19 == 0 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.6.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleBy23(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 23 == 0 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 1.7.1
// -----------------------------------------------------------------------------
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 29.
func divisibleBy29(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 29 == 0 {
count += 1
}
}
return count
if i.isOneDigit() { // value of type 'Int' has no member 'isOneDigit'
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
func divisibleBySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBySeven(n - 1)
}
func divisibleByEleven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByEleven(n - 1)
}
func divisibleByThirteen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirteen(n - 1)
}
func divisibleBySeventeen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBySeventeen(n - 1)
}
func divisibleByNineteen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByNineteen(n - 1)
}
func divisibleByTwentyThree(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByTwentyThree(n - 1)
}
func divisibleByTwentyNine(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByTwentyNine(n - 1)
}
func divisibleByThirtyOne(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirtyOne(n - 1)
}
func divisibleByThirtySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirtySeven(n - 1)
}
func divisibleByFourtyOne(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFourtyOne(n - 1)
}
func divisibleByFourtySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFourtySeven(n - 1)
}
func divisibleByFiftyThree(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFiftyThree(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
// 2.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 7.
func divisibleBySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBySeven(n - 1)
}
// 3.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleByEleven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByEleven(n - 1)
}
// 4.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleByThirteen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirteen(n - 1)
}
// 5.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBySeventeen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBySeventeen(n - 1)
}
// 6.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleByNineteen(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByNineteen(n - 1)
}
// 7.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleByTwentyThree(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByTwentyThree(n - 1)
}
// 8.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 29.
func divisibleByTwentyNine(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByTwentyNine(n - 1)
}
// 9.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 31.
func divisibleByThirtyOne(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirtyOne(n - 1)
}
// 10.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 37.
func divisibleByThirtySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByThirtySeven(n - 1)
}
// 11.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 41.
func divisibleByFourtyOne(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFourtyOne(n - 1)
}
// 12.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 47.
func divisibleByFourtySeven(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFourtySeven(n - 1)
}
// 13.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 53.
func divisibleByFiftyThree(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleByFiftyThree(n - 1)
}
// 14.
return n == 1 ? 1 : 1 + startsOneEnds(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBySeven(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByEleven(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByThirteen(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBySeventeen(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByNineteen(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByTwentyThree(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByTwentyNine(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByThirtyOne(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByThirtySeven(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByFourtyOne(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByFourtySeven(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleByFiftyThree(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
func divisibleBySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 7 * divisibleBySeven(n - 1)
}
func divisibleByEleven(n: Int) -> Int {
if n == 1 {
return 1
}
return 11 * divisibleByEleven(n - 1)
}
func divisibleByThirteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 13 * divisibleByThirteen(n - 1)
}
func divisibleBySeventeen(n: Int) -> Int {
if n == 1 {
return 1
}
return 17 * divisibleBySeventeen(n - 1)
}
func divisibleByNineteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 19 * divisibleByNineteen(n - 1)
}
func divisibleByTwentyThree(n: Int) -> Int {
if n == 1 {
return 1
}
return 23 * divisibleByTwentyThree(n - 1)
}
func divisibleByTwentyNine(n: Int) -> Int {
if n == 1 {
return 1
}
return 29 * divisibleByTwentyNine(n - 1)
}
func divisibleByThirtyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 31 * divisibleByThirtyOne(n - 1)
}
func divisibleByThirtySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 37 * divisibleByThirtySeven(n - 1)
}
func divisibleByFortyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 41 * divisibleByFortyOne(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 2
}
return 10 * startsOneEnds(n - 1)
}
// 2.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 7.
func divisibleBySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 7 * divisibleBySeven(n - 1)
}
// 3.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleByEleven(n: Int) -> Int {
if n == 1 {
return 1
}
return 11 * divisibleByEleven(n - 1)
}
// 4.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleByThirteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 13 * divisibleByThirteen(n - 1)
}
// 5.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBySeventeen(n: Int) -> Int {
if n == 1 {
return 1
}
return 17 * divisibleBySeventeen(n - 1)
}
// 6.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleByNineteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 19 * divisibleByNineteen(n - 1)
}
// 7.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleByTwentyThree(n: Int) -> Int {
if n == 1 {
return 1
}
return 23 * divisibleByTwentyThree(n - 1)
}
// 8.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 29.
func divisibleByTwentyNine(n: Int) -> Int {
if n == 1 {
return 1
}
return 29 * divisibleByTwentyNine(n - 1)
}
// 9.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 31.
func divisibleByThirtyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 31 * divisibleByThirtyOne(n - 1)
}
// 10.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 37.
func divisibleByThirtySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 37 * divisibleByThirtySeven(n - 1)
}
// 11.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 41.
func divisibleByFortyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 41 * divisibleByFortyOne(n - 1)
}
// 12.
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 47.
func divisibleByFortySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 47 * divisibleByFortySeven(n -
return 10 * startsOneEnds(n - 1) // missing argument label 'n:' in call
return 7 * divisibleBySeven(n - 1) // missing argument label 'n:' in call
return 11 * divisibleByEleven(n - 1) // missing argument label 'n:' in call
return 13 * divisibleByThirteen(n - 1) // missing argument label 'n:' in call
return 17 * divisibleBySeventeen(n - 1) // missing argument label 'n:' in call
return 19 * divisibleByNineteen(n - 1) // missing argument label 'n:' in call
return 23 * divisibleByTwentyThree(n - 1) // missing argument label 'n:' in call
return 29 * divisibleByTwentyNine(n - 1) // missing argument label 'n:' in call
return 31 * divisibleByThirtyOne(n - 1) // missing argument label 'n:' in call
return 37 * divisibleByThirtySeven(n - 1) // missing argument label 'n:' in call
return 41 * divisibleByFortyOne(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
if i.toString().first! == "1" || i.toString().last! == "1" {
count += 1
}
}
return count
}
func sumDigits(n: Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func trailingZeroes(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes2(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes3(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes4(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes5(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes6(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
func trailingZeroes7(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...n {
if i.toString().first! == "1" || i.toString().last! == "1" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 2. Given a positive integer n, return the sum of the digits of n.
func sumDigits(n: Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// -----------------------------------------------------------------------------
// 3. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 4. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes2(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 5. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes3(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 6. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes4(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 7. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes5(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 8. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes6(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 9. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes7(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// -----------------------------------------------------------------------------
// 10. Given an integer n, return the number of trailing zeroes in n!.
func trailingZeroes8(n: Int) -> Int {
var count = 0
if i.toString().first! == "1" || i.toString().last! == "1" { // value of type 'Int' has no member 'toString'
if i.toString().first! == "1" || i.toString().last! == "1" { // value of type 'Int' has no member 'toString'
n /= 10 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + startsOneEnds(n - 1)
}
func divisibleBySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleBySeven(n - 1)
}
func divisibleByEleven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByEleven(n - 1)
}
func divisibleByThirteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirteen(n - 1)
}
func divisibleBySeventeen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleBySeventeen(n - 1)
}
func divisibleByNineteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByNineteen(n - 1)
}
func divisibleByTwentyThree(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByTwentyThree(n - 1)
}
func divisibleByTwentyNine(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByTwentyNine(n - 1)
}
func divisibleByThirtyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirtyOne(n - 1)
}
func divisibleByThirtySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirtySeven(n - 1)
}
func divisibleByFortyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByFortyOne(n - 1)
}
func divisibleByFortySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByFortySeven(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + startsOneEnds(n - 1)
}
// 2. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 7.
func divisibleBySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleBySeven(n - 1)
}
// 3. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleByEleven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByEleven(n - 1)
}
// 4. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleByThirteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirteen(n - 1)
}
// 5. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBySeventeen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleBySeventeen(n - 1)
}
// 6. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleByNineteen(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByNineteen(n - 1)
}
// 7. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleByTwentyThree(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByTwentyThree(n - 1)
}
// 8. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 29.
func divisibleByTwentyNine(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByTwentyNine(n - 1)
}
// 9. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 31.
func divisibleByThirtyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirtyOne(n - 1)
}
// 10. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 37.
func divisibleByThirtySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByThirtySeven(n - 1)
}
// 11. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 41.
func divisibleByFortyOne(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByFortyOne(n - 1)
}
// 12. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 47.
func divisibleByFortySeven(n: Int) -> Int {
if n == 1 {
return 1
}
return 1 + divisibleByFortySeven(n - 1)
}
// 13. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are
return 1 + startsOneEnds(n - 1) // missing argument label 'n:' in call
return 1 + divisibleBySeven(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByEleven(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByThirteen(n - 1) // missing argument label 'n:' in call
return 1 + divisibleBySeventeen(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByNineteen(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByTwentyThree(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByTwentyNine(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByThirtyOne(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByThirtySeven(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByFortyOne(n - 1) // missing argument label 'n:' in call
return 1 + divisibleByFortySeven(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
return 10 * startsOneEnds(n - 1)
}
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with
return 10 * startsOneEnds(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
func divisibleBy11(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy11(n - 1)
}
func divisibleBy13(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy13(n - 1)
}
func divisibleBy17(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy17(n - 1)
}
func divisibleBy19(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy19(n - 1)
}
func divisibleBy23(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy23(n - 1)
}
func divisibleBy29(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy29(n - 1)
}
func divisibleBy31(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy31(n - 1)
}
func divisibleBy41(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy41(n - 1)
}
func divisibleBy51(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy51(n - 1)
}
func divisibleBy61(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy61(n - 1)
}
func divisibleBy71(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy71(n - 1)
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
// 1.1.2
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleBy11(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy11(n - 1)
}
// 1.1.3
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleBy13(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy13(n - 1)
}
// 1.1.4
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBy17(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy17(n - 1)
}
// 1.1.5
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleBy19(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy19(n - 1)
}
// 1.1.6
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleBy23(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy23(n - 1)
}
// 1.1.7
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 29.
func divisibleBy29(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy29(n - 1)
}
// 1.1.8
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 31.
func divisibleBy31(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy31(n - 1)
}
// 1.1.9
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 41.
func divisibleBy41(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy41(n - 1)
}
// 1.1.10
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 51.
func divisibleBy51(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy51(n - 1)
}
// 1.1.11
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 61.
func divisibleBy61(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy61(n - 1)
}
// 1.1.12
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 71.
func divisibleBy71(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy71(n - 1)
}
// 1.1.13
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 81.
func divisibleBy81(n: Int) -> Int {
return n == 1 ? 1 : 1 + divisibleBy81(n - 1
return n == 1 ? 1 : 1 + startsOneEnds(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy11(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy13(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy17(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy19(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy23(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy29(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy31(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy41(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy51(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy61(n - 1) // missing argument label 'n:' in call
return n == 1 ? 1 : 1 + divisibleBy71(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
return 1 + n
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
return 1 + n
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "1", count: i))) <= n {
count += 1
}
}
return count
}
func divisibleByThree(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "3", count: i))) % 3 == 0 {
count += 1
}
}
return count
}
func divisibleByFive(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "5", count: i))) % 5 == 0 {
count += 1
}
}
return count
}
func divisibleBySeven(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "7", count: i))) % 7 == 0 {
count += 1
}
}
return count
}
func divisibleByEleven(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "11", count: i))) % 11 == 0 {
count += 1
}
}
return count
}
func divisibleByThirteen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "13", count: i))) % 13 == 0 {
count += 1
}
}
return count
}
func divisibleBySeventeen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "17", count: i))) % 17 == 0 {
count += 1
}
}
return count
}
func divisibleByNineteen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "19", count: i))) % 19 == 0 {
count += 1
}
}
return count
}
func divisibleByTwentyThree(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "23", count: i))) % 23 == 0 {
count += 1
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "1", count: i))) <= n {
count += 1
}
}
return count
}
// 2. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 3.
func divisibleByThree(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "3", count: i))) % 3 == 0 {
count += 1
}
}
return count
}
// 3. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 5.
func divisibleByFive(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "5", count: i))) % 5 == 0 {
count += 1
}
}
return count
}
// 4. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 7.
func divisibleBySeven(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "7", count: i))) % 7 == 0 {
count += 1
}
}
return count
}
// 5. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 11.
func divisibleByEleven(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "11", count: i))) % 11 == 0 {
count += 1
}
}
return count
}
// 6. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 13.
func divisibleByThirteen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "13", count: i))) % 13 == 0 {
count += 1
}
}
return count
}
// 7. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 17.
func divisibleBySeventeen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "17", count: i))) % 17 == 0 {
count += 1
}
}
return count
}
// 8. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 19.
func divisibleByNineteen(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "19", count: i))) % 19 == 0 {
count += 1
}
}
return count
}
// 9. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 23.
func divisibleByTwentyThree(n: Int) -> Int {
var count = 0
for i in 1..<n {
if Int(String(String(repeating: "23", count: i))) % 23 == 0 {
count += 1
}
}
return count
}
// 10. Given a positive integer n, return the count of the numbers of n-digit
// positive integers that are divisible by 2
if Int(String(String(repeating: "1", count: i))) <= n { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "3", count: i))) % 3 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "5", count: i))) % 5 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "7", count: i))) % 7 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "11", count: i))) % 11 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "13", count: i))) % 13 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "17", count: i))) % 17 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "19", count: i))) % 19 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if Int(String(String(repeating: "23", count: i))) % 23 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
func withoutFirstAndLast(s: String) -> String {
return s[1..<s.count - 1]
}
func isNot(s: String) -> Bool {
return s.count(for: "is") == s.count(for: "not")
}
func everyOther(s: String) -> String {
return String(s[...])
}
func firstTwoEnds(s: String) -> Bool {
return s.count >= 2 && s.prefix(2) == s.suffix(2)
}
func exchangeFirstAndLast(s: String) -> String {
return String(s.last() + s[1..<s.count - 1] + s[0])
}
func exchangeFirstAndSecond(s: String) -> String {
return String(s[1] + s[0] + s[2..<s.count])
}
func lastTwoToStart(s: String) -> String {
return String(s[s.count - 2..<s.count]) + s[0..<s.count - 2]
}
func startsWithHi(s: String) -> Bool {
return s.prefix(2) == "hi"
}
func exchangeFirstAndLast(s: String) -> String {
return String(s[s.count - 1] + s[1..<s.count - 1] + s[0])
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
return n == 1 ? 1 : 1 + startsOneEnds(n - 1)
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given a string, return the string without the first and last character,
// so "Hello" yields "ell". The string length will be at least 2.
func withoutFirstAndLast(s: String) -> String {
return s[1..<s.count - 1]
}
// -----------------------------------------------------------------------------
// 1.1.3
// Given a string, return true if the number of appearances of "is" anywhere
// in the string is equal to the number of appearances of "not" anywhere in
// the string (case sensitive).
func isNot(s: String) -> Bool {
return s.count(for: "is") == s.count(for: "not")
}
// -----------------------------------------------------------------------------
// 1.1.4
// Given a string, return a new string made of every other character starting
// with the first, so "Hello" yields "Hlo".
func everyOther(s: String) -> String {
return String(s[...])
}
// -----------------------------------------------------------------------------
// 1.1.5
// Given a string, return true if the first 2 chars in the string also appear
// at the end of the string, such as with "edited".
func firstTwoEnds(s: String) -> Bool {
return s.count >= 2 && s.prefix(2) == s.suffix(2)
}
// -----------------------------------------------------------------------------
// 1.1.6
// Given a string, return a new string where the first and last chars have been
// exchanged.
func exchangeFirstAndLast(s: String) -> String {
return String(s.last() + s[1..<s.count - 1] + s[0])
}
// -----------------------------------------------------------------------------
// 1.1.7
// Given a string, return a new string where the first and second chars have been
// exchanged.
func exchangeFirstAndSecond(s: String) -> String {
return String(s[1] + s[0] + s[2..<s.count])
}
// -----------------------------------------------------------------------------
// 1.1.8
// Given a string, return a new string where the last 2 chars have been moved
// to the start. The string length will be at least 2.
func lastTwoToStart(s: String) -> String {
return String(s[s.count - 2..<s.count]) + s[0..<s.count - 2]
}
// -----------------------------------------------------------------------------
// 1.1.9
// Given a string, return true if the string starts with "hi" and false otherwise.
func startsWithHi(s: String) -> Bool {
return s.prefix(2) == "hi"
}
// -----------------------------------------------------------------------------
// 1.1.10
// Given a string, return a new string where the first and last chars have been
// exchanged.
func exchangeFirstAndLast(s: String) -> String {
return String(s[s.count - 1] + s[1..<s.count - 1] + s[0])
}
// ---------------------------------------------
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 2.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 3.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 4.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 5.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 6.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N /= 2
}
return binary
}
// 7.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "11
N /= 2 // left side of mutating operator isn't mutable: 'N' is a 'let' constant
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
N = N / 2 // cannot assign to value: 'N' is a 'let' constant
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
N = N / 2 // cannot assign to value: 'N' is a 'let' constant
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 2. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 3. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 4. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 5. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 6. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// 7. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve
N = N / 2 // cannot assign to value: 'N' is a 'let' constant
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N:
// XCTAssertTrue failed
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
while N > 0 {
binary = String(N % 2) + binary
N = N / 2
}
return binary
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
N = N / 2 // cannot assign to value: 'N' is a 'let' constant
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var n = N
while n > 0 {
binary = String(n % 2) + binary
n = n / 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
//
// XCTAssertTrue failed
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var binary = ""
var num = N
while num > 0 {
binary = String(num % 2) + binary
num /= 2
}
return binary
}
// Task
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 1
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 10. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 11. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 12. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 13. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 14. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 15. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 16. Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1
// XCTAssertTrue failed
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 2.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 3.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 4.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 5.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 6.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 7.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
let binary = String(UInt(N), radix: 2)
return binary
}
// 8.
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
func kthLargest(lst: [Int], k: Int) -> Int {
var sorted = lst.sorted()
return sorted[sorted.count - k]
}
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Given an array of integers lst and an integer k, return the kth largest element in the array.
// Examples:
// kthLargest(lst: [1, 2, 3, 4, 5], k: 3) == 4
// kthLargest(lst: [1, 2, 3, 4, 5], k: 1) == 5
func kthLargest(lst: [Int], k: Int) -> Int {
var sorted = lst.sorted()
return sorted[sorted.count - k]
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(str: String) -> Int {
var sum = 0
for char in str {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.
// Examples:
// sumNumbers
var sorted = lst.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += Int(char) // no exact matches in call to initializer
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).filter({ $0 % 2 == 1 }).reduce(0, \
\( \
\($0 + \($1))
)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).filter({ $0 % 2 == 1 }).reduce(0, \
\( \
\($0 + \($1))
)
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return lst.filter({ $0 % 2 == 0 }).filter({ $0 % 2 == 1 }).reduce(0, \ // missing argument for parameter #2 in call
\( \ // expected expression path in Swift key path
func add(lst: [Int]) -> Int {
return lst.filter({$0 % 2 == 0 && $0 % 2 != 0}).reduce(0, \+\)
}
func missing(lst: [Int]) -> Int {
return lst.filter({$0 > 0}).sorted().first(where: {$0 != 1}) ?? 1
}
func maxDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({$0 % 2 == 0 && $0 % 2 != 0}).reduce(0, \+\)
}
// 2.
// Given a non-empty array of integers lst. find the minimal positive integer that is not present in the array.
// Examples:
// missing([1, 3, 6, 4, 1, 2]) == 5
func missing(lst: [Int]) -> Int {
return lst.filter({$0 > 0}).sorted().first(where: {$0 != 1}) ?? 1
}
// 3.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxDiff([1, 2, 3, 4, 5]) == 4
// maxDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 4.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 5.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 6.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 7.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 8.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
// 9.
// Given a non-empty array of integers lst. find the maximal absolute difference between any two of its elements.
// Examples:
// maxAbsDiff([1, 2, 3, 4, 5]) == 4
// maxAbsDiff([-10, -9, -1, 2, 3, 4]) == 10
func maxAbsDiff(lst: [Int]) -> Int {
return lst.map({$0 * -1}).sorted().last()!
}
//
return lst.filter({$0 % 2 == 0 && $0 % 2 != 0}).reduce(0, \+\) // missing argument for parameter #2 in call
return lst.filter({$0 % 2 == 0 && $0 % 2 != 0}).reduce(0, \+\) // expected expression path in Swift key path
return lst.map({$0 * -1}).sorted().last()! // type of expression is ambiguous without a type annotation
return lst.map({$0 * -1}).sorted().last()! // type of expression is ambiguous without a type annotation
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, { $0 + $1 })
}
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, { $0 + $1 })
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, +)
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) ->
func add(lst: [Int]) -> Int { // invalid redeclaration of 'add(lst:)'
func add(lst: [Int]) -> Int { // invalid redeclaration of 'add(lst:)'
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
func minimal(lst: [Int]) -> Int {
var min = 1
for i in lst {
if i < min {
min = i
}
}
return min
}
func maximal(lst: [Int], n: Int) -> Int {
var max = 0
for i in lst {
if i > max && lst.count(i) <= n {
max = i
}
}
return max
}
func minimalDivisor(lst: [Int]) -> Int {
var min = 1
for i in lst {
if i % min == 0 {
min = i
} else {
break
}
}
return min
}
func maximalRepeat(lst: [Int]) -> Int {
var max = 0
for i in lst {
if lst.count(i) > max {
max = i
}
}
return max
}
func minimalRepeat(lst: [Int]) -> Int {
var min = 1
for i in lst {
if lst.count(i) < min {
min = i
}
}
return min
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Given a non-empty array of integers lst. find the minimal positive integer that does not occur in it.
// Examples:
// minimal(lst: [1, 3, 6, 4, 1, 2]) == 5
// minimal(lst: [-1, -3, -6, -4, -1, -2]) == 1
// minimal(lst: [1, 1, 1, 1]) == 2
func minimal(lst: [Int]) -> Int {
var min = 1
for i in lst {
if i < min {
min = i
}
}
return min
}
// Given a non-empty array of integers lst. find the maximal element that occurs no more than n times.
// Examples:
// maximal(lst: [1, 3, 6, 4, 1, 2], n: 2) == 3
// maximal(lst: [1, 3, 6, 4, 1, 2], n: 3) == 6
// maximal(lst: [1, 1, 1, 1], n: 1) == 1
func maximal(lst: [Int], n: Int) -> Int {
var max = 0
for i in lst {
if i > max && lst.count(i) <= n {
max = i
}
}
return max
}
// Given a non-empty array of integers lst. find the minimal k such that some pair of elements of lst is divisible by k.
// Examples:
// minimalDivisor(lst: [2, 4, 6, 8, 10]) == 2
// minimalDivisor(lst: [1, 3, 5, 7, 9]) == 1
// minimalDivisor(lst: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]) == 2
func minimalDivisor(lst: [Int]) -> Int {
var min = 1
for i in lst {
if i % min == 0 {
min = i
} else {
break
}
}
return min
}
// Given a non-empty array of integers lst. find the maximal element that occurs n times.
// Examples:
// maximalRepeat(lst: [1, 3, 6, 4, 1, 2]) == 3
// maximalRepeat(lst: [1, 1, 1, 1]) == 1
func maximalRepeat(lst: [Int]) -> Int {
var max = 0
for i in lst {
if lst.count(i) > max {
max = i
}
}
return max
}
// Given a non-empty array of integers lst. find the minimal element that occurs n times.
// Examples:
// minimalRepeat(lst: [1, 3, 6, 4, 1, 2]) == 1
// minimalRepeat(lst: [1, 1, 1, 1]) == 1
func minimalRepeat(lst: [Int]) -> Int {
var min = 1
for i in lst {
if lst.count(i) < min {
min = i
}
}
return min
}
// Given a non-empty array of integers lst. find the maximal element that occurs exactly once.
// Examples:
// maximalUnrepeat(lst: [1, 3, 6, 4, 1, 2]) == 6
// maximalUnrepeat(lst: [1, 1, 1, 1]) == 1
func maximalUnrepeat(lst: [Int]) -> Int {
var max = 0
for i in lst {
if lst.count(i) == 1 {
if i > max {
max = i
}
}
if i > max && lst.count(i) <= n { // cannot call value of non-function type 'Int'
if lst.count(i) > max { // cannot call value of non-function type 'Int'
if lst.count(i) < min { // cannot call value of non-function type 'Int'
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).filter({ $0 % 2 != 0 }).reduce(0, \
\( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \( \
XCTAssertTrue(Solution.add(lst: [4, 88]) == 88) // module 'Solution' has no member named 'add'
XCTAssertTrue(Solution.add(lst: [4, 5, 6, 7, 2, 122]) == 122) // module 'Solution' has no member named 'add'
XCTAssertTrue(Solution.add(lst: [4, 0, 6, 7]) == 0) // module 'Solution' has no member named 'add'
XCTAssertTrue(Solution.add(lst: [4, 4, 6, 8]) == 12) // module 'Solution' has no member named 'add'
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
func firstTwo(str: String) -> String {
if str.count < 2 {
return str
}
return str[0..<2]
}
func fizzString(str: String) -> String {
if str.first == "f" && str.last == "b" {
return "FizzBuzz"
} else if str.first == "f" {
return "Fizz"
} else if str.last == "b" {
return "Buzz"
}
return str
}
func arrayFront9(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 9 {
return true
}
if i == 3 {
return false
}
}
return false
}
func array123(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3 {
return true
}
}
return false
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// 2.
// Given a string str, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
// Examples:
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(str: String) -> String {
if str.count < 2 {
return str
}
return str[0..<2]
}
// 3.
// Given a string str, if the string starts with "f" return "Fizz". If the string ends with "b" return "Buzz". If both the "f" and "b" conditions are true, return "FizzBuzz". In all other cases, return the string unchanged.
// Examples:
// fizzString("fig") == "Fizz"
// fizzString("dib") == "Buzz"
// fizzString("fib") == "FizzBuzz"
// fizzString("dib") == "Buzz"
// fizzString("fizzbag") == "FizzBuzz"
func fizzString(str: String) -> String {
if str.first == "f" && str.last == "b" {
return "FizzBuzz"
} else if str.first == "f" {
return "Fizz"
} else if str.last == "b" {
return "Buzz"
}
return str
}
// 4.
// Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.
// Examples:
// arrayFront9([1, 2, 9, 3, 4]) == true
// arrayFront9([1, 2, 3, 4, 9]) == false
// arrayFront9([1, 2, 3, 4, 5]) == false
func arrayFront9(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 9 {
return true
}
if i == 3 {
return false
}
}
return false
}
// 5.
// Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere.
// Examples:
// array123([1, 1, 2, 3, 1]) == true
// array123([1, 1, 2, 4, 1]) == false
// array123([1, 1, 2, 1, 2, 3]) == true
func array123(nums: [Int]) -> Bool {
for i in 0..<nums.count {
if nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3 {
return true
}
}
return false
}
// 6.
// Given 2 strings, a and b, return a new string made of the first char of a and the last char of b, so "yo" and "java" yields "ya". If either string is length 0, use '@' for its missing char.
// Examples:
// lastChars("last", "chars") == "ls"
// lastChars("yo", "java") == "ya"
// lastChars("hi", "") == "h@"
// lastChars("", "be") == "@b"
// lastChars("", "") == "@@"
func lastChars(a: String, b: String) -> String {
var
return str[0..<2] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element })
}
// or
func add(lst: [Int]) -> Int {
func add(lst: [Int]) -> Int { // invalid redeclaration of 'add(lst:)'
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // extra argument in call
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // expected ',' separator
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return lst.filter({ $0 % 2 == 0 }).reduce(0, \(sum, element) { sum + element }) // string interpolation can only appear inside a string literal
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// Task
// Given a non-empty array of integers lst. add the even elements that are at odd indices.
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 1..<lst.count {
if lst[i] % 2 == 0 {
sum += lst[i]
}
}
return sum
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map { $0.sorted().joined(separator: "") }
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map { $0.sorted().joined(separator: "") }
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
var orderedWords = words.map { $0.sorted().joined(separator: "") } // no exact matches in call to instance method 'joined'
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
let ascii = UInt(UInt($0.asciiValue))
return String(ascii: ascii)
}
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
let ascii = UInt(UInt($0.asciiValue))
return String(ascii: ascii)
}
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
let ascii = UInt(UInt($0.asciiValue)) // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var result = ""
for word in words {
let sorted = word.sorted()
result += String(sorted) + " "
}
return result.trim()
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var result = ""
for word in words {
let sorted = word.sorted()
result += String(sorted) + " "
}
return result.trim()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
return result.trim() // value of type 'String' has no member 'trim'
func antiShuffle(s: String) -> String {
var result = ""
var words = s.split(" ")
for word in words {
var chars = word.characters
var sortedChars = chars.sorted()
result += String(sortedChars) + " "
}
return result.trim()
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var result = ""
var words = s.split(" ")
for word in words {
var chars = word.characters
var sortedChars = chars.sorted()
result += String(sortedChars) + " "
}
return result.trim()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
var words = s.split(" ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
return orderedWords.joined(separator: " ")
}
}
// -----------------------------------------------------------------------------
struct StringShuffler {
static func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map {
let ascii = UInt($0.asciiValue)
return String(ascii: ascii)
}
return String(characters: chars, count: chars.count)
}
let ascii = UInt($0.asciiValue) // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let ascii = UInt($0.asciiValue) // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map { $0.sorted().joined(separator: "") }
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map { $0.sorted().joined(separator: "") }
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
var orderedWords = words.map { $0.sorted().joined(separator: "") } // no exact matches in call to instance method 'joined'
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var result = ""
for word in words {
let sorted = word.map(String.init).sorted()
result += String(sorted) + " "
}
return result.trim()
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var result = ""
for word in words {
let sorted = word.map(String.init).sorted()
result += String(sorted) + " "
}
return result.trim()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
result += String(sorted) + " " // no exact matches in call to initializer
return result.trim() // value of type 'String' has no member 'trim'
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map { $0.characters }
chars.sorted()
return String(chars)
}
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.split(separator: " ")
var orderedWords = words.map {
let chars = $0.map { $0.characters }
chars.sorted()
return String(chars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
let chars = $0.map { $0.characters } // value of type 'Substring.Element' (aka 'Character') has no member 'characters'
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
Character($0.asciiValue)
}.sorted()
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
Character($0.asciiValue)
}.sorted()
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
Character($0.asciiValue)
}.sorted()
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
Character($0.asciiValue)
}.sorted()
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var words = s.split(separator: " ")
var orderedWords = words.map {
let sortedChars = $0.map {
Character($0.asciiValue)
}.sorted()
return String(sortedChars)
}
return orderedWords.joined(separator: " ")
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
//
Character($0.asciiValue) // no exact matches in call to initializer
func antiShuffle(s: String) -> String {
var result = ""
var words = s.split(" ")
for word in words {
var sorted = ""
for char in word {
sorted += String(char)
}
result += sorted + " "
}
return result.trim()
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
var result = ""
var words = s.split(" ")
for word in words {
var sorted = ""
for char in word {
sorted += String(char)
}
result += sorted + " "
}
return result.trim()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
var words = s.split(" ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
for i in 0..<result.count {
result[i].sort(by: { $0 > $1 })
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
for i in 0..<result.count {
result[i].sort(by: { $0 > $1 })
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
var result = [] // empty collection literal requires an explicit type
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result[i].sort(by: { $0 > $1 }) // value of type 'Any' has no member 'sort'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
// 2.
// Given an array of integers, return the sum of the first value in the array,
// followed by the last value in the array, then the second value in the array,
// then the second to last value in the array, and so on.
// You should assume that the array will always contain at least one element.
// Examples:
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6]) == 12
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7]) == 20
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8]) == 28
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9]) == 36
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 45
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 55
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 66
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 78
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 91
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 105
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 120
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 136
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 152
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 168
// sumFirstLast(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
var result = [] // empty collection literal requires an explicit type
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.forEach { (i, j) in // contextual closure type '(Any) throws -> Void' expects 1 argument, but 2 were used in closure body
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
struct Coordinate {
var row: Int
var column: Int
}
func removeVowels(s: String) -> String {
var result = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Coordinate {
var row: Int
var column: Int
}
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test" yields "Ths s tst".
// You should ignore case.
// Y is not a vowel.
//
// Example:
// removeVowels("Hello") == "Hll"
// removeVowels("C is fun!") == "C s fnn!"
// removeVowels("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func removeVowels(s: String) -> String {
var result = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func removeVowels(s: String) -> String {
var result = ""
for c in s {
if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" {
result += c
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
func removeVowels(s: String) -> String {
var result = ""
var result = [] // empty collection literal requires an explicit type
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort()
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort()
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
// -----------------------------------------------------------------------------
// 1.10
// Given a string, return a new string with all the vowels removed.
// For example, "This is a test" yields "Ths s tst".
// Assume the vowels are {'a', 'e', 'i', 'o', 'u'}.
// Examples:
// removeVowels("This is a test") == "Ths s tst"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("aeiouaeiouaeiou") == ""
// removeVowels("aeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiouaeiou
var result = [] // empty collection literal requires an explicit type
result.sort() // type 'Any' cannot conform to 'Comparable'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 })
}
struct Coordinate {
var row: Int
var column: Int
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct Coordinate {
var row: Int
var column: Int
}
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 })
}<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is "wke", with the length of 3.
// Note that the answer must be a substring, "pwke" is a subsequence and not a
// substring.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
var result = [] // empty collection literal requires an explicit type
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 }) // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '0'
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '0'
return result.sorted(by: { $0.0 < $1.0 }).sorted(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 < $1.1 })
}
return result
}
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 < $1.1 })
}
return result
}
// 2. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
// 3. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
// 4. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
// 5. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
// 6. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String) -> String {
var result = ""
for char in str {
result += String(char) + String(char)
}
return result
}
// 7. Write a function that takes a string as input and returns a string
// in which each character is repeated once.
// Examples:
// doubleChar("String") == "SSttrriinngg"
// doubleChar("Hello World!") == "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") == "11223344!!__ "
func doubleChar(str: String
var result = [] // empty collection literal requires an explicit type
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.forEach { (i, j) in // contextual closure type '(Any) throws -> Void' expects 1 argument, but 2 were used in closure body
result.sort(by: { $0.1 < $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 < $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in lst {
var count = 0
for j in i {
if j == x {
count += 1
}
}
result.append((lst.index(i), count))
}
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 }
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in lst {
var count = 0
for j in i {
if j == x {
count += 1
}
}
result.append((lst.index(i), count))
}
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
var result = [] // empty collection literal requires an explicit type
result.append((lst.index(i), count)) // missing argument label 'of:' in call
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // value of type 'Any' has no member '0'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // value of type 'Any' has no member '0'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // value of type 'Any' has no member '1'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // value of type 'Any' has no member '0'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // value of type 'Any' has no member '1'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // cannot convert value of type 'Int' to closure result type 'Bool'
return result.sorted(by: { $0.1 < $1.1 ? -1 : 1 }).sorted(by: { $0.0 < $1.0 ? -1 : 1 }).map { $0.0 } // cannot convert value of type 'Int' to closure result type 'Bool'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort()
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort()
result.sort(by: { $0.0 < $1.0 })
result.sort(by: { $0.1 > $1.1 })
return result
}
// 2.
// Given a string, return a string with the characters in reverse order.
// Examples:
// reverse("hello") == "olleh"
// reverse("hello world") == "dlrow olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("a b c") == "c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z" == "z y x w v u t s r q p o n m l k j i h g f e d c b
var result = [] // empty collection literal requires an explicit type
result.sort() // type 'Any' cannot conform to 'Comparable'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
var result = [] // empty collection literal requires an explicit type
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.sort(by: { $0.0 < $1.0 }) // value of type 'Any' has no member '0'
result.forEach { (i, j) in // contextual closure type '(Any) throws -> Void' expects 1 argument, but 2 were used in closure body
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
result.sort(by: { $0.1 > $1.1 }) // value of type 'Any' has no member '1'
return result // cannot convert return expression of type '[Any]' to return type '[(Int, Int)]'
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
func alphabetize(s: String) -> String {
return String(s.sorted())
}
func sumOfPositives(lst: [Int]) -> Int {
var result = 0
for i in lst {
if i > 0 {
result += i
}
}
return result
}
func flipEndChars(s: String) -> String {
if s.count == 0 {
return ""
}
if s.count == 1 {
return s
}
if s.count == 2 {
return s[1...] + s[0]
}
return s[1...] + s[0] + s[s.count - 1... 1]
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = []
for i in 0..<lst.count {
for j in 0..<lst[i].count {
if lst[i][j] == x {
result.append((i, j))
}
}
}
result.sort(by: { $0.0 < $1.0 })
result.forEach { (i, j) in
result.sort(by: { $0.1 > $1.1 })
}
return result
}
// 2.
// Given a string, return a string with the letters in alphabetical order.
// Examples:
// alphabetize("hello") == "ehllo"
// alphabetize("edabit") == "abdeit"
// alphabetize("") == ""
// alphabetize("a") == "a"
// alphabetize("zyxwvutsrqponmlkjihgfedcba") == "abcdefghijklmnopqrstuvwxyz"
// alphabetize("Zbcdefg") == "abcdefgZ"
func alphabetize(s: String) -> String {
return String(s.sorted())
}
// 3.
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Examples:
// sumOfPositives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sumOfPositives([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
// sumOfPositives([-1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 55
// sumOfPositives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 135
func sumOfPositives(lst: [Int]) -> Int {
var result = 0
for i in lst {
if i > 0 {
result += i
}
}
return result
}
// 4.
// Given a string, return a new string with the first and last characters swapped.
// Examples:
// flipEndChars("cat") == "tcat"
// flipEndChars("Hello") == "oHell"
// flipEndChars("a") == "a"
// flipEndChars("") == ""
// flipEndChars("1234") == "4321"
// flipEndChars("123456789") == "987654321"
func flipEndChars(s: String) -> String {
if s.count == 0 {
return ""
}
if s.count == 1 {
return s
}
if s.count == 2 {
return s[1...] + s[0]
}
return s[1...] + s[0] + s[s.count - 1... 1]
}
// 5.
// Given a string, return a new string with all the vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " prtr"
// removeVowels("hello!") == " hll!"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("1234
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
array.sort(by: { $0 < $1 })
} else {
array.sort(by: { $0 > $1 })
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
array.sort(by: { $0 < $1 })
} else {
array.sort(by: { $0 > $1 })
}
return array
}
// 2.
// Given a string, return a new string with all the vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn psl ndng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " pr t"
// removeVowels("hello world") == "hll wrld"
// removeVowels("ciao mondo!") == "cj mjnd!"
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree")
array.sort(by: { $0 < $1 }) // cannot use mutating member on immutable value: 'array' is a 'let' constant
array.sort(by: { $0 > $1 }) // cannot use mutating member on immutable value: 'array' is a 'let' constant
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.10.1
// Given an array of integers, return the sum of all the integers that are in the array.
// Note:
// * don't change the given array.
// Examples:
// sumArray(array: []) == 0
// sumArray(array: [1]) == 1
// sumArray(array: [1, 2]) == 3
// sumArray(array: [1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.10.2
// Given an array of integers, return the sum of all the integers that are in the array.
// Note:
// * don't change the given array.
// Examples:
// sumArray(array: []) == 0
// sumArray(array: [1]) == 1
// sumArray(array: [1, 2]) == 3
// sumArray(array: [1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.10.3
// Given an array of integers, return the sum of all the integers that are in the array.
// Note:
// * don't change the given array.
// Examples:
// sumArray(array: []) == 0
// sumArray(array: [1]) == 1
// sumArray(array: [1, 2]) == 3
// sumArray(array: [1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.10.4
// Given an array of integers, return the sum of all the integers that are in the array.
// Note:
// * don't change the given array.
// Examples:
// sumArray(array: []) == 0
// sumArray(array: [1]) == 1
// sumArray(array: [1, 2]) == 3
// sumArray(array: [1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.10.5
// Given an array of integers, return the sum of all the integers that are in the array.
// Note:
// * don't change the given array.
// Examples:
// sumArray(array: []) == 0
// sumArray(array: [1]) == 1
// sumArray(array: [1, 2]) == 3
// sumArray(array: [1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, \(sum, element) { sum + element })
}
return array.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return array.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return array.reduce(0, \(sum, element) { sum + element }) // extra argument in call
return array.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return array.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return array.reduce(0, \(sum, element) { sum + element }) // string interpolation can only appear inside a string literal
return array.reduce(0, \(sum, element) { sum + element }) // expected ',' separator
return array.reduce(0, \(sum, element) { sum + element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
return sum % 2 == 0 ? array.sorted(by: <) : array.sorted(by: >)
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
return sum % 2 == 0 ? array.sorted(by: <) : array.sorted(by: >)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
if (result.count > 0) {
var sum = result[0] + result[result.count - 1]
if (sum % 2 == 0) {
result.sort(by: { $0 < $1 })
} else {
result.sort(by: { $0 > $1 })
}
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var result = array
if (result.count > 0) {
var sum = result[0] + result[result.count - 1]
if (sum % 2 == 0) {
result.sort(by: { $0 < $1 })
} else {
result.sort(by: { $0 > $1 })
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
var sum = result[0] + result[result.count - 1] // variable 'sum' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
}
// ----------------------------------------------------------------------------------------------------------------------
// swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
}
// ----------------------------------------------------------------------------------------------------------------------
// swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
}
// ----------------------------------------------------------------------------------------------------------------------
// swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
let sum = array.first! + array.last!
return sum % 2 == 0 ? array.sorted(by: >) : array.sorted(by: <)
}
//
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if (array[0] + array[array.count - 1]) % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if (array[0] + array[array.count - 1]) % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var sortedArray = array
var sum = 0
for i in 0..<sortedArray.count {
sum += sortedArray[i]
}
if sum % 2 == 0 {
sortedArray.sort(by: <)
} else {
sortedArray.sort(by: >)
}
return sortedArray
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var sortedArray = array
var sum = 0
for i in 0..<sortedArray.count {
sum += sortedArray[i]
}
if sum % 2 == 0 {
sortedArray.sort(by: <)
} else {
sortedArray.sort(by: >)
}
return sortedArray
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//------------------
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
var sum = array[0] + array[array.count - 1] // variable 'sum' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var result = array
var sum = result[0] + result[result.count - 1]
if sum % 2 == 0 {
result.sort(by: <)
} else {
result.sort(by: >)
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var result = array
var sum = result[0] + result[result.count - 1]
if sum % 2 == 0 {
result.sort(by: <)
} else {
result.sort(by: >)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
var sum = result[0] + result[result.count - 1] // variable 'sum' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
let sum = array[0] + array[array.count - 1]
if sum % 2 == 0 {
return array.sorted()
} else {
return array.sorted().reversed()
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = ascii + 2
if newAscii > 122 {
newAscii = newAscii - 26
}
result += String(ascii: newAscii)
} else if ascii >= 65 && ascii <= 90 {
let newAscii = ascii + 2
if newAscii > 90 {
newAscii = newAscii - 26
}
result += String(ascii: newAscii)
} else {
result += String(char)
}
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = ascii + 2
if newAscii > 122 {
newAscii = newAscii - 26
}
result += String(ascii: newAscii)
} else if ascii >= 65 && ascii <= 90 {
let newAscii = ascii + 2
if newAscii > 90 {
newAscii = newAscii - 26
}
result += String(ascii: newAscii)
} else {
result += String(char)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let newAscii = ascii + 2 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
result += String(ascii: newAscii) // no exact matches in call to initializer
} else if ascii >= 65 && ascii <= 90 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
} else if ascii >= 65 && ascii <= 90 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let newAscii = ascii + 2 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
result += String(ascii: newAscii) // no exact matches in call to initializer
func encrypt(s: String) -> String {
var result = ""
for char in s {
var ascii = char.asciiValue
if ascii >= 65 && ascii <= 90 {
ascii += 2
if ascii > 90 {
ascii -= 26
}
} else if ascii >= 97 && ascii <= 122 {
ascii += 2
if ascii > 122 {
ascii -= 26
}
}
result += String(char: ascii)
}
return result
}
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
var ascii = char.asciiValue
if ascii >= 65 && ascii <= 90 {
ascii += 2
if ascii > 90 {
ascii -= 26
}
} else if ascii >= 97 && ascii <= 122 {
ascii += 2
if ascii > 122 {
ascii -= 26
}
}
result += String(char: ascii)
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "hello world") == "dlrow olleh"
// reverse(s: "") == ""
func
if ascii >= 65 && ascii <= 90 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii >= 65 && ascii <= 90 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
ascii += 2 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii > 90 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
ascii -= 26 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
} else if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
} else if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
ascii += 2 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii > 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
ascii -= 26 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
result += String(char: ascii) // no exact matches in call to initializer
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.firstIndex(of: char)!
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.firstIndex(of: char)!
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let newIndex = (index + 2) % alphabet.count // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
var result = ""
for char in s {
if char.isAsciiLetter {
let ascii = char.asciiValue
let newAscii = ascii + 2 * 2
let newChar = Character(newAscii)
result += newChar
} else {
result += char
}
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
if char.isAsciiLetter {
let ascii = char.asciiValue
let newAscii = ascii + 2 * 2
let newChar = Character(newAscii)
result += newChar
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
if char.isAsciiLetter { // value of type 'Character' has no member 'isAsciiLetter'
let newAscii = ascii + 2 * 2 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.firstIndex(of: char)!
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.firstIndex(of: char)!
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let newIndex = (index + 2) % alphabet.count // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.index(of: char)
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in s {
let index = alphabet.index(of: char)
let newIndex = (index + 2) % alphabet.count
result += alphabet[newIndex]
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let index = alphabet.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
let newIndex = (index + 2) % alphabet.count // cannot convert value of type 'String.Index?' to expected argument type 'Int'
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char)
let newAscii = ascii + 2
let newChar = String(newAscii)
result += newChar
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = Int(char)
let newAscii = ascii + 2
let newChar = String(newAscii)
result += newChar
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let ascii = Int(char) // no exact matches in call to initializer
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for char in s {
let index = alphabet.firstIndex(of: char)
if index == nil {
encrypted += char
} else {
let newIndex = (index! + 2) % 26
encrypted += alphabet[newIndex]
}
}
return encrypted
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var encrypted = ""
for char in s {
let index = alphabet.firstIndex(of: char)
if index == nil {
encrypted += char
} else {
let newIndex = (index! + 2) % 26
encrypted += alphabet[newIndex]
}
}
return encrypted
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as an argument and returns a string
// with the letters in reverse order.
// For example:
// reverse(s: "hello") == "olleh"
// reverse(s: "goodbye") == "eybdoog"
// reverse(s: "") == ""
// reverse(s: "a") == "a"
// reverse(s: "a b c") == "c b a"
// reverse(s: "a-b-c") == "c-b-a"
// reverse(s: "a.b.c") == "c.b.a"
// reverse(s: "a,b,c") == "c,b,a"
// reverse(s: "a;b;c") == "c;b;a"
// reverse(s: "a(b)(c)") == "c(b)(a)"
// reverse(s: "a[b][c]") == "c[b][a]"
// reverse(s: "a{b}{c}") == "c{b}{a}"
// reverse(s: "a<b><c>") == "c<b><a>"
// reverse(s: "a>b>c") == "c>b>a"
// reverse(s: "a?b?c") == "c?b?a"
// reverse(s: "a!b!c") == "c!b!a"
// reverse(s: "a~b~c") == "c~b~a"
// reverse(s: "a|b|c") == "c|b|a"
// reverse(s: "a\\b\\c") == "c\\b\\a"
// reverse(s: "a/b/c") == "c/b/a"
// reverse(s: "a-b-c") == "c-b-a"
// reverse(s: "a.b.c") == "c.b.a"
// reverse(s: "a,b,c") == "c,b,a"
// reverse(s: "a;b;c") == "c;b;a"
// reverse(s: "a(b)(c)") == "c(b)(a)"
// reverse(s: "a[b][c]") == "c[b][a]"
// reverse(s: "a{b}{c}") == "c{b}{a}"
// reverse(s: "a<b><c>") == "c<b><a>"
// reverse(s: "a>b>c") == "c>b>a"
// reverse(s: "a?b?c") == "c?b?a"
// reverse(s: "a!b!c") == "c!b!a"
// reverse(s: "a~b~c") == "c~b~a"
// reverse(s: "a|b|c") == "c|b|a"
// reverse(s: "a\\b\\c") == "c\\b\\a"
// reverse(s: "a/b/c") == "c/b/a"
// reverse(s: "a-b-c") == "c-b-a"
// reverse(s: "a.b.c") == "c.b.a"
// reverse(s: "a,b,c") == "c,b,a"
// reverse(s: "a;b;c") == "c;b;a"
// reverse(s: "a(b)(c)") == "c(b)(a)"
// reverse(s: "a[
encrypted += char // cannot convert value of type 'Character' to expected argument type 'String'
let newIndex = (index! + 2) % 26 // cannot convert value of type 'String.Index' to expected argument type 'Int'
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = (ascii - 97 + 2) % 26 + 97
result += String(UnicodeScalar(newAscii))
} else {
result += String(char)
}
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = (ascii - 97 + 2) % 26 + 97
result += String(UnicodeScalar(newAscii))
} else {
result += String(char)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let newAscii = (ascii - 97 + 2) % 26 + 97 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = (ascii - 97 + 2) % 26 + 97
result += String(Character(newAscii))
} else {
result += String(char)
}
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for char in s {
let ascii = char.asciiValue
if ascii >= 97 && ascii <= 122 {
let newAscii = (ascii - 97 + 2) % 26 + 97
result += String(Character(newAscii))
} else {
result += String(char)
}
}
return result
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ------
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if ascii >= 97 && ascii <= 122 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let newAscii = (ascii - 97 + 2) % 26 + 97 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n = n >> 1
}
return count
}
func countBits(x: Int, y: Int) -> Int {
var count = 0
var xor = x ^ y
while xor > 0 {
if xor & 1 == 1 {
count += 1
}
xor = xor >> 1
}
return count
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// -----------------------------------------------------------------------------
// 1.1
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.2
// Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// Given n = 11 (0000 1011), return 3.
// Note:
// Note that since C does not have unsigned int, using signed int is fine.
// You may assume that your compiler can store the result of n in a 32-bit
// variable without overflowing.
func countOnes(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n = n >> 1
}
return count
}
// -----------------------------------------------------------------------------
// 1.3
// Write a function that takes an integer and returns the number of bits that are
// different in the binary representation of x and y.
// Example:
// countBits(5, 9) == 2
// countBits(7, 10) == 1
// countBits(11, 12) == 2
// countBits(10, 10) == 0
// countBits(0, 0) == 0
// countBits(1, 2) == 1
// countBits(1234, 5678) == 110011
// countBits(1, 1) == 0
// countBits(21, 33) == 3
// countBits(10000, 00000) == 12
// countBits(11111111, 11111111) == 30
// countBits(0, 11111111) == 31
// countBits(11111111, 0) == 31
// countBits(1234, 5678) == 110011
// countBits(1, 2) == 1
// countBits(1234, 5678) == 110011
// countBits(1, 1) == 0
// countBits(21, 33) == 3
// countBits(10000, 00000) == 12
// countBits(11111111, 11111111) == 30
// countBits(0, 11111111) == 31
// countBits(11111111, 0) == 31
func countBits(x: Int, y: Int) -> Int {
var count = 0
var xor = x ^ y
while xor > 0 {
if xor & 1 == 1 {
count += 1
}
xor = xor >> 1
}
return count
}
// -----------------------------------------------------------------------------
// 1.4
// Write a function that takes a string and returns the first character that
// appears more than once.
n = n >> 1 // cannot assign to value: 'n' is a 'let' constant
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
import Foundation
func reverseString(s: String) -> String {
return String(s.reverse())
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
func containsDuplicate(nums: [Int]) -> Bool {
var result = false
var dict = [Int: Int]()
for i in 0..<nums.count {
if dict[nums[i]] != nil {
result = true
break
} else {
dict[nums[i]] = 1
}
}
return result
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
print(nextSmallest([1, 2, 3, 4, 5]))
print(nextSmallest([5, 1, 4, 3, 2]))
print(nextSmallest([] as [Int]))
print(nextSmallest([1, 1]))<|endoftext|>//
// main.swift
// Swift_Exercises
//
// Created by Javier on 11/11/15.
// Copyright © 2015 Javier. All rights reserved.
//
import Foundation
// 1. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reverse())
}
print(reverseString("hello"))
// 2. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
print(twoSum([2, 7, 11, 15], 9))
// 3. Given an array of integers, find if the array contains any duplicates.
// Your function should return true if any value appears at least twice in the array,
// and it should return false if every element is distinct.
// Example 1:
// Input: [1,2,3,1]
// Output: true
// Example 2:
// Input: [1,2,3,4]
// Output: false
// Example 3:
// Input: [1,1,1,3,3,4,3,2,4,2]
// Output: true
func containsDuplicate(nums: [Int]) -> Bool {
var result = false
var dict = [Int: Int]()
for i in 0..<nums.count {
if dict[nums[i]] != nil {
result = true
break
} else {
dict[nums[i]] = 1
}
}
return result
}
print(containsDuplicate([1,2,3,1]))
print(containsDuplicate([1,2,3,4]))
print(containsDuplicate([1,1,1,3,3,4,3,2,4,2]))
// 4. Given an array of integers, find if the array contains any duplicates.
// Your function should return true if any value appears at least twice in the array,
// and it should return false if every element is distinct.
// Example 1:
// Input: [1,2,3,1]
// Output: true
// Example 2:
// Input: [1,2,3,4]
// Output: false
// Example 3:
// Input: [1,1,1,3,3,4,3,2,4,2]
// Output: true
func containsDuplicate(nums: [Int]) -> Bool {
return String(s.reverse()) // value of type 'String' has no member 'reverse'
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = Int.max
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = Int.max
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// 10. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 11. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 12. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 13. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 14. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 15. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
// 16. Write a function that returns the number of times a given character occurs in a string.
// nextCharacterCount("apple", "p") == 2
// nextCharacterCount("apple", "z") == 0
// nextCharacterCount("", "z") == 0
func nextCharacterCount(string: String, character: String) -> Int {
var count = 0
for i in string {
if i == character {
count += 1
}
}
return count
}
//
if i == character { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
func nextLargest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var max = lst[0]
var secondMax = lst[1]
for i in lst {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
return secondMax
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// 2. Write a function that returns the 2nd largest element of the array.
// Return nil if there is no such element.
// nextLargest(lst: [1, 2, 3, 4, 5]) == 4
// nextLargest(lst: [5, 1, 4, 3, 2]) == 4
// nextLargest(lst: [] as [Int]) == nil
// nextLargest(lst: [1, 1]) == nil
func nextLargest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var max = lst[0]
var secondMax = lst[1]
for i in lst {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
return secondMax
}
// 3. Write a function that returns the 2nd largest element of the array.
// Return nil if there is no such element.
// nextLargest(lst: [1, 2, 3, 4, 5]) == 4
// nextLargest(lst: [5, 1, 4, 3, 2]) == 4
// nextLargest(lst: [] as [Int]) == nil
// nextLargest(lst: [1, 1]) == nil
func nextLargest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var max = lst[0]
var secondMax = lst[1]
for i in lst {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
return secondMax
}
// 4. Write a function that returns the 2nd largest element of the array.
// Return nil if there is no such element.
// nextLargest(lst: [1, 2, 3, 4, 5]) == 4
// nextLargest(lst: [5, 1, 4, 3, 2]) == 4
// nextLargest(lst: [] as [Int]) == nil
// nextLargest(lst: [1, 1]) == nil
func nextLargest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var max = lst[0]
var secondMax = lst[1]
for i in lst {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
return secondMax
}
// 5. Write a function that returns the 2nd largest element of the array.
// Return nil if there is no such element.
// nextLargest(lst: [1, 2, 3, 4, 5]) == 4
// nextLargest(lst: [5, 1, 4, 3, 2]) == 4
// nextLargest(lst: [] as [Int]) == nil
// nextLargest(lst: [1, 1]) == nil
func nextLargest(lst: [Int]) -> Int? {
if lst.count < 2 {
return nil
}
var max = lst[0]
var secondMax = lst[1]
for i in lst {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
return secondMax
}
// 6. Write a function that returns the 2
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
import Foundation
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
print(nextSmallest([1, 2, 3, 4, 5]))
print(nextSmallest([5, 1, 4, 3, 2]))
print(nextSmallest([] as [Int]))
print(nextSmallest([1, 1]))<|endoftext|>//
// main.swift
// Swift-Interview-Questions
//
// Created by 임성민 on 2020/04/24.
// Copyright © 2020 임성민. All rights reserved.
//
import Foundation
// 1. 주어진 문자열을 뒤집어서 반환하는 함수를 작성하세요.
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
// 예) "apple" -> "elppa"
//
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[0]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[0]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
print(nextSmallest([1, 2, 3, 4, 5]))
print(nextSmallest([5, 1, 4, 3, 2]))
print(nextSmallest([] as [Int]))
print(nextSmallest([1, 1]))
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
import Foundation
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
print(nextSmallest([1, 2, 3, 4, 5]))
print(nextSmallest([5, 1, 4, 3, 2]))
print(nextSmallest([] as [Int]))
print(nextSmallest([1, 1]))<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/04.
//
import Foundation
var num = 0
while num < 100 {
num += 1
if num % 3 == 0 {
print("Fizz")
} else if num % 5 == 0 {
print("Buzz")
} else {
print(num)
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/04.
//
import Foundation
var num = 0
while num < 100 {
num += 1
if num % 3 == 0 {
print("Fizz")
} else if num % 5 == 0 {
print("Buzz")
} else if num % 3 == 0 && num % 5 == 0 {
print("FizzBuzz")
} else {
print(num)
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/04.
//
import Foundation
var num = 0
while num < 100 {
num += 1
if num % 3 == 0 {
print("Fizz")
} else if num % 5 == 0 {
print("Buzz")
} else if num % 3 == 0 && num % 5 == 0 {
print("FizzBuzz")
} else {
print(num)
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/04.
//
import Foundation
var num = 0
while num < 100 {
num += 1
if num % 3 == 0 {
print("Fizz")
} else if num % 5 == 0 {
print("Buzz")
} else if num % 3 == 0 && num % 5 == 0 {
print("FizzBuzz")
} else {
print(num)
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/04.
//
import Foundation
var num = 0
while num < 100 {
num += 1
if num % 3 == 0 {
print("Fizz")
} else if num % 5 == 0 {
print("Buzz")
} else if num % 3 == 0 && num % 5 == 0 {
print("FizzBuzz")
} else {
print(num)
}
}<|endoftext|>//
// main.swift
// 1
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return lst[0]
}
var min = lst[0]
var secondMin = lst[0]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return lst[0]
}
var min = lst[0]
var secondMin = lst[0]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
func add(a: String, b: String) -> Int {
return Int(a) + Int(b)
}
func divide(a: Int, b: Int) -> Float {
return Float(a) / Float(b)
}
func addBinary(a: Int, b: Int) -> String {
return String(a + b)
}
func digitize(n: Int) -> [Int] {
return String(n).map { $0 }.map { Int($0) }
}
func fakeBin(s: String) -> String {
return s.map { $0 }.map { $0 < "5" ? "0" : "1" }.join()
}
func high(s: String) -> String {
let words = s.split(separator: " ")
var scores = words.map { $0.map { $0 }.map { Int($0) }.map { $0 } }
var max = scores[0]
for i in scores {
if i > max {
max = i
}
}
var index = scores.firstIndex(of: max)
return words[index]
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
if lst.count == 1 {
return nil
}
var min = lst[0]
var secondMin = lst[1]
for i in lst {
if i < min {
secondMin = min
min = i
} else if i < secondMin {
secondMin = i
}
}
return secondMin
}
// 2. Write a function that returns the sum of two numbers.
// The two numbers are passed as strings.
// Example: add("123", "321") // returns 444
func add(a: String, b: String) -> Int {
return Int(a) + Int(b)
}
// 3. Write a function that returns the remainder of dividing two numbers.
// Division should be accurate to three decimal places.
// Example: divide(7, 2) // returns 3.5
func divide(a: Int, b: Int) -> Float {
return Float(a) / Float(b)
}
// 4. Write a function that adds two numbers together and returns their sum in binary.
// The conversion can be done before, or after the addition.
// The binary number returned should be a string.
// Examples:
// addBinary(1, 1) == "100"
// addBinary(5, 9) == "111"
func addBinary(a: Int, b: Int) -> String {
return String(a + b)
}
// 5. Given a non-negative integer, return an array of the individual digits in order from most to least significant.
// Example:
// digitize(35231) == [1, 3, 2, 5, 3]
func digitize(n: Int) -> [Int] {
return String(n).map { $0 }.map { Int($0) }
}
// 6. Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.
// Note: input will never be an empty string
// Example:
// fakeBin("45385593107843568") == "01011110001100111"
func fakeBin(s: String) -> String {
return s.map { $0 }.map { $0 < "5" ? "0" : "1" }.join()
}
// 7. Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Example:
// high("man i need a taxi up to ubud") == "taxi"
// high("what time are we climbing up to the volcano") == "volcano"
// high("take me to semynak") == "semynak"
func high(s: String) -> String {
let words = s.split(separator: " ")
var scores = words.map { $0.map { $0 }.map { Int($0) }.map { $0 } }
var max = scores[0]
for i in scores {
if i > max {
max = i
}
}
var index = scores.firstIndex(of: max)
return words[index]
}
// 8. Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Example:
// high("man i need a taxi up to ubud"
return Int(a) + Int(b) // binary operator '+' cannot be applied to two 'Int?' operands
return String(n).map { $0 }.map { Int($0) } // type '()' cannot conform to 'BinaryInteger'
return s.map { $0 }.map { $0 < "5" ? "0" : "1" }.join() // value of type '[String]' has no member 'join'
var scores = words.map { $0.map { $0 }.map { Int($0) }.map { $0 } } // no exact matches in call to initializer
return words[index] // no 'subscript' candidates produce the expected contextual result type 'String'
func isBored(S: String) -> Int {
let words = S.split(".")
let count = 0
for word in words {
if word.startsWith("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(".")
let count = 0
for word in words {
if word.startsWith("I") {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
let words = S.split(".") // no exact matches in call to instance method 'split'
func isBored(S: String) -> Int {
var count = 0
var words = S.split(" ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
var words = S.split(" ")
for word in words {
if word == "I" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ------------------------------
var words = S.split(" ") // no exact matches in call to instance method 'split'
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
for word in S.split(".") {
if word.startsWith("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
for word in S.split(".") {
if word.startsWith("I") {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Count the number of boredoms
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/5648b12ce6a07b5cc000099/train/swift
//
// You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. The list is ordered according to who signed up first.
//
// Your task is to return one of the following strings:
//
// < firstName here >, < country here > of the first Python developer who has signed up; or
// There will be no Python developers if no Python developer has signed up.
// For example, given the following input array:
//
// list1 = [
// { "firstName": "Mark", "lastName": "G.", "country": "Scotland", "continent": "Europe", "age": 22, "language": "JavaScript" },
// { "firstName": "Victoria", "lastName": "T.", "country": "Puerto Rico", "continent": "Americas", "age": 30, "language": "Python" },
// { "firstName": "Emma", "lastName": "B.", "country": "Norway", "continent": "Europe", "age": 19, "language": "Clojure" }
// ]
// your function should return Victoria, Puerto Rico.
//
// Notes:
// The input array will always be valid and formatted as in the example above.
//
// -----------------------------------------------------------------------------
// 12. Find the odd int
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/54da539698b8a2ad76000228/train/swift
//
// You are given an array with positive numbers and a non-negative number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0.
//
// Let's look at a few examples:
// array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
// array = [1, 2] and N = 3, but N is outside of the array, so the result is -1.
//
// -----------------------------------------------------------------------------
// 13. Find the odd int
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/54da539698b8a2ad76000228/train/swift
//
// You are given an array with positive numbers and a non-negative number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0.
//
// Let's look at a few examples:
// array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
// array = [1, 2] and N = 3, but N is outside of the array, so the result is -1.
//
// ------------------------------------
for word in S.split(".") { // no exact matches in call to instance method 'split'
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
func high(s: String) -> String {
let words = s.split(separator: " ")
var max = 0
var maxWord = ""
for word in words {
var score = 0
for letter in word {
score += letter.asciiValue - 96
}
if score > max {
max = score
maxWord = word
}
}
return maxWord
}
func doubleChar(s: String) -> String {
var result = ""
for letter in s {
result += letter + letter
}
return result
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 10.
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the
// alphabet: a = 1, b = 2, c = 3 etc.
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest
// in the original string.
// All letters will be lowercase and all inputs will be valid.
func high(s: String) -> String {
let words = s.split(separator: " ")
var max = 0
var maxWord = ""
for word in words {
var score = 0
for letter in word {
score += letter.asciiValue - 96
}
if score > max {
max = score
maxWord = word
}
}
return maxWord
}
// -----------------------------------------------------------------------------
// 11.
// Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(s: String) -> String {
var result = ""
for letter in s {
result += letter + letter
}
return result
}
// -----------------------------------------------------------------------------
// 12.
// Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(s: String) -> String {
var result = ""
for letter in s {
result += letter + letter
}
return result
}
// -----------------------------------------------------------------------------
// 13.
// Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(s: String) -> String {
var result = ""
for letter in s {
result += letter + letter
}
return result
}
// -----------------------------------------------------------------------------
// 14.
// Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(s: String) -> String {
var result = ""
for letter in s {
result += letter + letter
}
return result
}
// ------------
score += letter.asciiValue - 96 // cannot convert value of type 'UInt8?' to expected argument type 'Int'
maxWord = word // cannot assign value of type 'String.SubSequence' (aka 'Substring') to type 'String'
result += letter + letter // binary operator '+=' cannot be applied to operands of type 'String' and '_'
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
func mostFrequent(S: String) -> String {
let words = S.split(separator: " ")
var mostFrequentWord = ""
var mostFrequentCount = 0
var currentCount = 0
for word in words {
currentCount = 0
for otherWord in words {
if word == otherWord {
currentCount += 1
}
}
if currentCount > mostFrequentCount {
mostFrequentWord = word
mostFrequentCount = currentCount
}
}
return mostFrequentWord
}
func high(S: String) -> String {
let words = S.split(separator: " ")
var highestScore = 0
var highestScoreWord = ""
for word in words {
var score = 0
for letter in word {
score += letter.asciiValue - "a".asciiValue + 1
}
if score > highestScore {
highestScore = score
highestScoreWord = word
}
}
return highestScoreWord
}
func doubleChar(S: String) -> String {
var doubledString = ""
for letter in S {
doubledString += letter.stringValue + letter.stringValue
}
return doubledString
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word.first! == "I" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. You'll be given a string of words. You have to find the most frequent
// word in the string. If there are two or more words that occur the same amount
// of times, return the string that comes first in the original string.
// For example:
// mostFrequent("a a a b b b b") == "a"
// mostFrequent("a b c") == "a"
// mostFrequent("a b b b b b") == "b"
func mostFrequent(S: String) -> String {
let words = S.split(separator: " ")
var mostFrequentWord = ""
var mostFrequentCount = 0
var currentCount = 0
for word in words {
currentCount = 0
for otherWord in words {
if word == otherWord {
currentCount += 1
}
}
if currentCount > mostFrequentCount {
mostFrequentWord = word
mostFrequentCount = currentCount
}
}
return mostFrequentWord
}
// -----------------------------------------------------------------------------
// 13. Given a string of words, you need to find the highest scoring word.
// For this problem, a word's score is the sum of the alphabet's positions
// in the word. For example, the word value for "helium" is 404.
// All letters will be given in lowercase.
// If two words have the same score, the word that appears first in the
// original string is the winner.
// For example:
// high("hello world") == "world"
// high("codewars") == "codewars"
// high("internationalization") == "internationalization"
// high("exercism") == "exercism"
func high(S: String) -> String {
let words = S.split(separator: " ")
var highestScore = 0
var highestScoreWord = ""
for word in words {
var score = 0
for letter in word {
score += letter.asciiValue - "a".asciiValue + 1
}
if score > highestScore {
highestScore = score
highestScoreWord = word
}
}
return highestScoreWord
}
// -----------------------------------------------------------------------------
// 14. Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(S: String) -> String {
var doubledString = ""
for letter in S {
doubledString += letter.stringValue + letter.stringValue
}
return doubledString
}
// -----------------------------------------------------------------------------
// 15. Given a string, you have to return a string in which each character
// (case-sensitive) is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
func doubleChar(S: String) -> String {
var doubledString = ""
for letter in S {
doubledString += letter.stringValue + letter.
mostFrequentWord = word // cannot assign value of type 'String.SubSequence' (aka 'Substring') to type 'String'
score += letter.asciiValue - "a".asciiValue + 1 // value of type 'String' has no member 'asciiValue'
score += letter.asciiValue - "a".asciiValue + 1 // cannot convert value of type 'UInt8?' to expected argument type 'Int'
highestScoreWord = word // cannot assign value of type 'String.SubSequence' (aka 'Substring') to type 'String'
doubledString += letter.stringValue + letter.stringValue // value of type 'Character' has no member 'stringValue'
doubledString += letter.stringValue + letter.stringValue // value of type 'Character' has no member 'stringValue'
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var counter = 0
for word in words {
if word == "I" {
counter += 1
}
}
return counter
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var counter = 0
for word in words {
if word == "I" {
counter += 1
}
}
return counter
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
// XCTAssertTrue failed
func isBored(S: String) -> Int {
return S.split(".").map(String.init).filter(String.init).count("I")
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
return S.split(".").map(String.init).filter(String.init).count("I")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
return S.split(".").map(String.init).filter(String.init).count("I") // cannot call value of non-function type 'Int'
return S.split(".").map(String.init).filter(String.init).count("I") // no exact matches in call to instance method 'filter'
return S.split(".").map(String.init).filter(String.init).count("I") // no exact matches in call to instance method 'split'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y && x > z
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y + z
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > (y + z) / 2
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > 20 || y + z > x * y * z
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y * z
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y * z / (y + z)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
// 2.
// Create a function that takes 3 numbers.
// Returns true if the last number is the greatest of the others, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y && x > z
}
// 3.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the sum of the others, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y + z
}
// 4.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the average of the others, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > (y + z) / 2
}
// 5.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than 20 or if the sum of the others is greater than the product of all, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > 20 || y + z > x * y * z
}
// 6.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the sum of the others, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y + z
}
// 7.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the product of the others, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y * z
}
// 8.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the product of the others divided by the sum, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y * z / (y + z)
}
// 9.
// Create a function that takes 3 numbers.
// Returns true if the last number is greater than the product of the others divided by the sum, and returns false otherwise.
// Examples
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 1, y: 3, z: 2) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return x > y * z
func isMax(x: Double, y: Double, z: Double) -> Bool { // invalid redeclaration of 'isMax(x:y:z:)'
func isMax(x: Double, y: Double, z: Double) -> Bool { // invalid redeclaration of 'isMax(x:y:z:)'
func isMax(x: Double, y: Double, z: Double) -> Bool { // invalid redeclaration of 'isMax(x:y:z:)'
func isMax(x: Double, y: Double, z: Double) -> Bool { // invalid redeclaration of 'isMax(x:y:z:)'
func isMax(x: Double, y: Double, z: Double) -> Bool { // invalid redeclaration of 'isMax(x:y:z:)'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
func addTen(num: Int) -> Int {
return num + 10
}
func subtractFive(num: Int) -> Int {
return num - 5
}
func addFive(num: Int) -> Int {
return num + 5
}
func multiplyByTen(num: Int) -> Int {
return num * 10
}
func divideByTen(num: Int) -> Int {
return num / 10
}
func reverse(num: Int) -> Int {
if num < 0 {
return num
} else {
let reversed = String(num).reversed()
return Int(String(reversed))
}
}
func stringify(num: Int) -> String {
if num < 0 {
return String(num)
} else {
return String(num)
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
// 3. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(num: Int) -> Int {
return num + 10
}
// 4. Create a function that takes a number as an argument.
// Subtract 5 from that number and return the result.
// Examples
// subtractFive(0) == -5
// subtractFive(1) == -6
// subtractFive(5) == 0
func subtractFive(num: Int) -> Int {
return num - 5
}
// 5. Create a function that takes a number as an argument.
// Add 5 to that number and return the result.
// Examples
// addFive(0) == 5
// addFive(1) == 6
// addFive(5) == 10
func addFive(num: Int) -> Int {
return num + 5
}
// 6. Create a function that takes a number as an argument.
// Multiply that number by 10 and return the result.
// Examples
// multiplyByTen(0) == 0
// multiplyByTen(1) == 10
// multiplyByTen(5) == 50
func multiplyByTen(num: Int) -> Int {
return num * 10
}
// 7. Create a function that takes a number as an argument.
// Divide that number by 10 and return the result.
// Examples
// divideByTen(0) == 0
// divideByTen(10) == 1
// divideByTen(100) == 10
func divideByTen(num: Int) -> Int {
return num / 10
}
// 8. Create a function that takes a number as an argument.
// If the number is negative, return it without changing.
// If it is positive, return it reversed.
// Examples
// reverse(15) == 51
// reverse(-15) == -15
// reverse(800) == 8
func reverse(num: Int) -> Int {
if num < 0 {
return num
} else {
let reversed = String(num).reversed()
return Int(String(reversed))
}
}
// 9. Create a function that takes a number as an argument.
// Convert the number to a string.
// If the number is negative, turn the string negative.
// If it is positive, leave it as a positive number.
// Examples
// stringify(4) == "4"
// stringify(-4) == "-4"
// stringify(0) == "0"
func stringify(num: Int) -> String {
if num < 0 {
return String(num)
} else {
return String(num)
}
}
// 10. Create a function that takes a number as an argument.
// If the number is a multiple of 3, return "Fizz".
// If the number is a multiple of 5, return "Buzz".
// If the number is a multiple of both 3 and 5, return "FizzBuzz".
// If it isn't a multiple of either, return the number.
// Examples
// fizzBuzz(3) == "Fizz"
// fizzBuzz(5) == "Buzz"
// fizzBuzz(15) == "FizzBuzz"
// fizzBuzz(4) == 4
func fizzBuzz(num: Int) -> String {
if num % 3 == 0 && num % 5 == 0 {
return "FizzBuzz"
} else if num % 3 == 0 {
return "Fizz"
} else if num % 5 == 0 {
return "Buzz"
} else {
return Int(String(reversed)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) ➞ 10
// addTen(9) ➞ 19
// addTen(-3) ➞ -3
// Notes
// Don't forget to return the result.
// If you get stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// Only JavaScript is supported.
// Some challenges have additional requirements for this challenge.
// ----------------------------------------------------------------------------------------------------------------------
// 12. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return value.
// Examples
// addValue(5) ➞ 15
// addValue(100) ➞ 100
// addValue(95) ➞ 95
// Notes
// Don't forget to return the result.
// If you get stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// Only JavaScript is supported.
// Some challenges have additional requirements for this challenge.
// ----------------------------------------------------------------------------------------------------------------------
// 13. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return value.
// Examples
// addValue(5) ➞ 15
// addValue(100) ➞ 100
// addValue(95) ➞ 95
// Notes
// Don't forget to return the result.
// If you get stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// Only JavaScript is supported.
// Some challenges have additional requirements for this challenge.
// ----------------------------------------------------------------------------------------------------------------------
// 14. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return value.
// Examples
// addValue(5) ➞ 15
// addValue(100) ➞ 100
// addValue(95) ➞ 95
// Notes
// Don't forget to return the result.
// If you get stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// If you're stuck on a challenge, find help in the Resources tab.
// Only JavaScript is supported.
// Some challenges have additional requirements for this challenge.
// ----------------------------------------------------------------------------------------------------------------------
// 15. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return value.
// Examples
// addValue(5) ➞ 1
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
func addTen(num: Int) -> Int {
return num + 10
}
func subTen(num: Int) -> Int {
return num - 10
}
func multTen(num: Int) -> Int {
return num * 10
}
func divTen(num: Int) -> Int {
return num / 10
}
func finalResult(num: Int) -> Int {
return (num + 80 - 50) / 3 * 5
}
func isGreaterThan100(num: Int) -> Bool {
if num > 100 {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
// Task 2
// Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(num: Int) -> Int {
return num + 10
}
// Task 3
// Create a function that takes a number as an argument.
// Subtract 10 from that number and return the result.
// Examples
// subTen(0) == -10
// subTen(10) == 0
// subTen(13) == 3
func subTen(num: Int) -> Int {
return num - 10
}
// Task 4
// Create a function that takes a number as an argument.
// Multiply that number by 10 and return the result.
// Examples
// multTen(0) == 0
// multTen(10) == 100
// multTen(100) == 10000
func multTen(num: Int) -> Int {
return num * 10
}
// Task 5
// Create a function that takes a number as an argument.
// Divide that number by 10 and return the result.
// Examples
// divTen(0) == 0
// divTen(100) == 10
// divTen(90) == 9
func divTen(num: Int) -> Int {
return num / 10
}
// Task 6
// Create a function that takes a number as an argument.
// Add 80 to that number.
// Subtract 50.
// Divide the result by 3.
// Multiply that result by 5.
// Return the final result.
// Examples
// finalResult(0) == 135
// finalResult(100) == 165
// finalResult(1000) == 1875
func finalResult(num: Int) -> Int {
return (num + 80 - 50) / 3 * 5
}
// Task 7
// Create a function that takes a number as an argument.
// Add 40 to that number.
// If that number is greater than 100, return `True`.
// Otherwise, return `False`.
// Examples
// isGreaterThan100(0) == False
// isGreaterThan100(100) == True
// isGreaterThan100(101) == True
// isGreaterThan100(105) == True
// isGreaterThan100(1000) == True
// isGreaterThan100(1001) == False
// isGreaterThan100(10000) == False
// isGreaterThan100(10001) == False
func isGreaterThan100(num: Int) -> Bool {
if num > 100 {
return true
} else {
return false
}
}
// Task 8
// Create a function that takes a number as an argument.
// Add 10 to that number.
// If that number is greater than 100, return `True`.
// Otherwise, return `False`.
// Examples
// isGreaterThan100(0) == False
// isGreaterThan100(100) == True
// isGreaterThan100(101) == True
// isGreaterThan100(105) == True
// isGreaterThan100(1000) == True
// isGreaterThan100(1001) == False
// isGreaterThan100(10000) == False
// isGreaterThan100(1
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
func addTen(num: Int) -> Int {
return num + 10
}
func subtractTen(num: Int) -> Int {
return num - 10
}
func multiplyTen(num: Int) -> Int {
return num * 10
}
func divideTen(num: Int) -> Int {
return num / 10
}
func reverse(num: Int) -> Int {
return num < 0 ? num : Int(String(num).reversed())
}
func stringify(num: Int) -> String {
return num < 0 ? "-" + String(num) : String(num)
}
func fizzBuzz(num: Int) -> String {
return num % 3 == 0 && num % 5 == 0 ? "FizzBuzz" : num % 3 == 0 ? "Fizz" : num % 5 == 0 ? "Buzz" : String(num)
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
// 4. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(num: Int) -> Int {
return num + 10
}
// 5. Create a function that takes a number as an argument.
// Subtract 10 from that number and return the result.
// Examples
// subtractTen(0) == -10
// subtractTen(9) == 9
// subtractTen(-8) == -18
func subtractTen(num: Int) -> Int {
return num - 10
}
// 6. Create a function that takes a number as an argument.
// Multiply that number by 10 and return the result.
// Examples
// multiplyTen(5) == 50
// multiplyTen(0) == 0
// multiplyTen(-8) == -80
func multiplyTen(num: Int) -> Int {
return num * 10
}
// 7. Create a function that takes a number as an argument.
// Divide that number by 10 and return the result.
// Examples
// divideTen(100) == 10
// divideTen(90) == 9
// divideTen(-80) == -0.8
func divideTen(num: Int) -> Int {
return num / 10
}
// 8. Create a function that takes a number as an argument.
// If the number is negative, return it without changing.
// If it is positive, return it reversed.
// Examples
// reverse(15) == 51
// reverse(-15) == -15
// reverse(7) == 7
func reverse(num: Int) -> Int {
return num < 0 ? num : Int(String(num).reversed())
}
// 9. Create a function that takes a number as an argument.
// Convert the number to a string.
// If the number is negative, turn the string negative.
// If it is positive, leave it as a positive string.
// Examples
// stringify(4) == "4"
// stringify(-4) == "-4"
// stringify(0) == "0"
func stringify(num: Int) -> String {
return num < 0 ? "-" + String(num) : String(num)
}
// 10. Create a function that takes a number as an argument.
// If the number is a multiple of 3, return "Fizz".
// If the number is a multiple of 5, return "Buzz".
// If the number is a multiple of both 3 and 5, return "FizzBuzz".
// If the number is not a multiple of either 3 or 5, return the number as a string.
// Examples
// fizzBuzz(3) == "Fizz"
// fizzBuzz(5) == "Buzz"
// fizzBuzz(15) == "FizzBuzz"
// fizzBuzz(4) == "4"
func fizzBuzz(num: Int) -> String {
return num % 3 == 0 && num % 5 == 0 ? "FizzBuzz" : num % 3 == 0 ? "Fizz" : num % 5 == 0 ? "Buzz" : String(num)
}
// 11. Create a function that takes a number as an argument.
// If the number is a multiple of 4, return "Fizz".
// If the number is a multiple of 3, return "Buzz".
// If the number is a multiple of both 3 and 4, return "FizzBuzz".
// If the number is not a multiple of either 3 or 4, return the number as a string.
// Examples
// fizzBuzz(3) == "Buzz"
// fizzBuzz(5) == "Fizz"
// fizzBuzz(
return num < 0 ? num : Int(String(num).reversed()) // no exact matches in call to initializer
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
func addTen(num: Int) -> Int {
return num + 10
}
func subtractTen(num: Int) -> Int {
return num - 10
}
func multiplyTen(num: Int) -> Int {
return num * 10
}
func divideTen(num: Int) -> Int {
return num / 10
}
func makePositive(num: Int) -> Int {
if num < 0 {
return num * -1
} else {
return num
}
}
func numberToString(num: Int) -> String {
return String(num)
}
func numberToString(num: Int) -> String {
if num < 0 {
return "-" + String(num)
} else {
return String(num)
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y) {
return true
} else {
return false
}
}
// 10. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(num: Int) -> Int {
return num + 10
}
// 11. Create a function that takes a number as an argument.
// Subtract 10 from that number and return the result.
// Examples
// subtractTen(0) == -10
// subtractTen(9) == 1
// subtractTen(-8) == -18
func subtractTen(num: Int) -> Int {
return num - 10
}
// 12. Create a function that takes a number as an argument.
// Multiply that number by 10 and return the result.
// Examples
// multiplyTen(5) == 50
// multiplyTen(-8) == -80
// multiplyTen(0) == 0
func multiplyTen(num: Int) -> Int {
return num * 10
}
// 13. Create a function that takes a number as an argument.
// Divide that number by 10 and return the result.
// Examples
// divideTen(100) == 10
// divideTen(90) == 9
// divideTen(0) == 0
func divideTen(num: Int) -> Int {
return num / 10
}
// 14. Create a function that takes a number as an argument.
// If the number is negative, convert it to positive and return it.
// Otherwise, return it as is.
// Examples
// makePositive(5) == 5
// makePositive(0) == 0
// makePositive(-7) == 7
func makePositive(num: Int) -> Int {
if num < 0 {
return num * -1
} else {
return num
}
}
// 15. Create a function that takes a number as an argument.
// Convert the number to a string and return it.
// Examples
// numberToString(0) == "0"
// numberToString(9) == "9"
// numberToString(-324) == "-324"
func numberToString(num: Int) -> String {
return String(num)
}
// 16. Create a function that takes a number as an argument.
// Convert the number to a string and return it.
// If the number is negative, add "-" to the beginning.
// Examples
// numberToString(0) == "0"
// numberToString(9) == "9"
// numberToString(-324) == "-324"
func numberToString(num: Int) -> String {
if num < 0 {
return "-" + String(num)
} else {
return String(num)
}
}
// 17. Create a function that takes a number as an argument.
// Convert the number to a string and return it.
// If the number is negative, add "-" to the beginning.
// Otherwise, return it as is.
// Examples
// numberToString(0) == "0"
// numberToString(9) == "9"
// numberToString(-324) == "-324"
func numberToString(num: Int) -> String {
if num < 0 {
return "-" + String(num)
} else {
return String(num)
}
}
// 18. Create a function that takes a number as an argument.
// Convert the number to a string and return it.
// If the number is negative, add "-" to the beginning.
// Otherwise, return it as is.
// If the number contains a 5, return "Dojo" instead.
// Examples
// numberToString(0) == "0"
// numberToString(9) == "9"
// numberToString(-3
func numberToString(num: Int) -> String { // invalid redeclaration of 'numberToString(num:)'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == x && Int(y) == y && Int(z) == z {
return true
}
return false
}
func addTen(num: Int) -> Int {
return num + 10
}
func multiplyTen(num: Int) -> Int {
return num * 10
}
func divideTen(num: Int) -> Int {
return num / 10
}
func fourTeen(num: Int) -> Int {
return (num + 8) * 4
}
func threeNine(num: Int) -> Int {
return (num - 4) * 3
}
func lessThan100(num: Int) -> String {
if num < 100 {
return "It's less than 100!"
} else {
return "It's greater than 100!"
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if Int(x) == x && Int(y) == y && Int(z) == z {
return true
}
return false
}
// 10. Create a function that takes a number as an argument.
// Add 10 to that number and return the value.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-3) == -3
func addTen(num: Int) -> Int {
return num + 10
}
// 11. Create a function that takes a number as an argument.
// Multiply that number by 10 and return the value.
// Examples
// multiplyTen(5) == 50
// multiplyTen(0) == 0
// multiplyTen(-8) == -80
func multiplyTen(num: Int) -> Int {
return num * 10
}
// 12. Create a function that takes a number as an argument.
// Divide that number by 10 and return the value.
// Examples
// divideTen(100) == 10
// divideTen(40) == 4
// divideTen(0) == 0
func divideTen(num: Int) -> Int {
return num / 10
}
// 13. Create a function that takes a number as an argument.
// Add 8 to that number, multiply that sum by 4, and return the value.
// Examples
// fourTeen(10) == 100
// fourTeen(0) == 0
// fourTeen(-4) == -12
func fourTeen(num: Int) -> Int {
return (num + 8) * 4
}
// 14. Create a function that takes a number as an argument.
// Subtract 4 from that number, multiply that number by 3, and return the value.
// Examples
// threeNine(10) == 15
// threeNine(0) == -12
// threeNine(-8) == -54
func threeNine(num: Int) -> Int {
return (num - 4) * 3
}
// 15. Create a function that takes a number as an argument.
// Add 20 to that number, return the result.
// If the result is greater than 100, return "It's greater than 100!".
// Otherwise, return "It's less than 100!".
// Examples
// lessThan100(50) == "It's less than 100!"
// lessThan100(100) == "It's greater than 100!"
// lessThan100(150) == "It's greater than 100!"
func lessThan100(num: Int) -> String {
if num < 100 {
return "It's less than 100!"
} else {
return "It's greater than 100!"
}
}
// 16. Create a function that takes a number as an argument.
// Add 20 to that number, return the result.
// If the result is greater than 100, return "It's greater than 100!".
// Otherwise, return "It's less than 100!".
// If the result is greater than 100, return "It's greater than 100!".
// Otherwise, return "It's less than 100!".
// Examples
// lessThan100(50) == "It's less than 100!"
// lessThan100(100) == "It's greater than 100!"
// lessThan100(150) == "It's greater than 100!"
func lessThan100(num: Int) -> String {
if num < 100 {
return "It's less than 100!"
} else {
return "It's greater than 100!"
}
}
// 17. Create a function
if Int(x) == x && Int(y) == y && Int(z) == z { // cannot convert value of type 'Double' to expected argument type 'Int'
if Int(x) == x && Int(y) == y && Int(z) == z { // cannot convert value of type 'Double' to expected argument type 'Int'
if Int(x) == x && Int(y) == y && Int(z) == z { // cannot convert value of type 'Double' to expected argument type 'Int'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
func addTen(number: Int) -> Int {
return number + 10
}
func multiplyTen(number: Int) -> Int {
return number * 10
}
func divideTen(number: Int) -> Int {
return number / 10
}
func finalResult(number: Int) -> Int {
return (number + 8 - 10) / 4 * 5
}
func finalResult(number: Int) -> Int {
return (number + 2) ** 2 / 2 - 8
}
func finalResult(number: Int) -> Int {
return (number + 2) ** 2 / 2 - 8 * 5
}
func hundred(number: Int) -> String {
if number > 100 {
return "Just above a hundred"
} else if number < 100 {
return "Just below a hundred"
} else {
return "Exactly a hundred"
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
// 12. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(number: Int) -> Int {
return number + 10
}
// 13. Create a function that takes a number as an argument.
// Multiply that number by 10 and return the result.
// Examples
// multiplyTen(5) == 50
// multiplyTen(0) == 0
// multiplyTen(-8) == -80
func multiplyTen(number: Int) -> Int {
return number * 10
}
// 14. Create a function that takes a number as an argument.
// Divide that number by 10 and return the result.
// Examples
// divideTen(100) == 10
// divideTen(90) == 9
// divideTen(0) == 0
func divideTen(number: Int) -> Int {
return number / 10
}
// 15. Create a function that takes a number as an argument.
// Add 8 to that number.
// Subtract 10 from that sum.
// Divide the result by 4.
// Multiply that result by 5.
// Return the final result.
// Examples
// finalResult(4) == 20
// finalResult(10) == 6
// finalResult(0) == 0
func finalResult(number: Int) -> Int {
return (number + 8 - 10) / 4 * 5
}
// 16. Create a function that takes a number as an argument.
// Add 2 to that number.
// Square that result.
// Divide the result by 2.
// Subtract 8 from the result.
// Return the final result.
// Examples
// finalResult(2) == 22
// finalResult(0) == 0
// finalResult(5) == 16
func finalResult(number: Int) -> Int {
return (number + 2) ** 2 / 2 - 8
}
// 17. Create a function that takes a number as an argument.
// Add 2 to that number.
// Square the result.
// Divide the result by 2.
// Subtract 8 from the result.
// Multiply that result by 5.
// Return the final result.
// Examples
// finalResult(2) == 22
// finalResult(0) == 0
// finalResult(5) == 16
func finalResult(number: Int) -> Int {
return (number + 2) ** 2 / 2 - 8 * 5
}
// 18. Create a function that takes a number as an argument.
// Add 10 to that number.
// If that number is greater than 100, return "Just above a hundred".
// If that number is less than 100, return "Just below a hundred".
// If that number is equal to 100, return "Exactly a hundred".
// Examples
// hundred(60) == "Just below a hundred"
// hundred(100) == "Exactly a hundred"
// hundred(110) == "Just above a hundred"
func hundred(number: Int) -> String {
if number > 100 {
return "Just above a hundred"
} else if number < 100 {
return "Just below a hundred"
} else {
return "Exactly a hundred"
}
}
// 19. Create a function that takes a number as an argument.
// Add 10 to that number.
// If that number is greater than 100, return "Just above a hundred".
// If that number is less than 100, return "Just below a hundred".
// If that number is equal to 100, return "Exactly a hundred"
func finalResult(number: Int) -> Int { // invalid redeclaration of 'finalResult(number:)'
return (number + 2) ** 2 / 2 - 8 // no operator '**' is defined; did you mean 'pow(_:_:)'?
func finalResult(number: Int) -> Int { // invalid redeclaration of 'finalResult(number:)'
return (number + 2) ** 2 / 2 - 8 * 5 // no operator '**' is defined; did you mean 'pow(_:_:)'?
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)) && Int(x) == Int(y) && Int(y) == Int(z)
}
func isMax(x: Double, y: Double, z: Double) -> Bool {
return Int(x) > Int(y) && Int(x) > Int(z)
}
func digitToLetter(n: Int) -> String {
return String(UnicodeScalar(n + 65))
}
func fizzBuzz(n: Int) -> String {
if n % 3 == 0 && n % 5 == 0 {
return "FizzBuzz"
} else if n % 3 == 0 {
return "Fizz"
} else if n % 5 == 0 {
return "Buzz"
} else {
return String(UnicodeScalar(n + 65))
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return (Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)) && Int(x) == Int(y) && Int(y) == Int(z)
}
// 3. Create a function that takes 3 numbers.
// Returns true if the last number is the greatest of the others, and false otherwise.
// Examples
// isMax(x: 5, y: 2, z: 2) == false
// isMax(x: 5, y: 3, z: 2) == true
// isMax(x: 5, y: 3, z: 3) == false
// isMax(x: 5.1, y: 3, z: 3) == false
func isMax(x: Double, y: Double, z: Double) -> Bool {
return Int(x) > Int(y) && Int(x) > Int(z)
}
// 4. Create a function that takes a number as an argument.
// Returns the letter corresponding to that digit in the English alphabet: 0 = A, 1 = B, 2 = C, etc.
// Examples
// digitToLetter(0) == "A"
// digitToLetter(1) == "B"
// digitToLetter(3) == "D"
// digitToLetter(10) == "A"
func digitToLetter(n: Int) -> String {
return String(UnicodeScalar(n + 65))
}
// 5. Create a function that takes a number as an argument.
// Returns the letter corresponding to that digit in the English alphabet: 0 = A, 1 = B, 2 = C, etc.
// However, for multiples of 3 (e.g. 3, 6, 9, etc.), return "Fizz".
// For multiples of 5 (e.g. 5, 10, etc.), return "Buzz".
// For multiples of both 3 and 5 (e.g. 15, 30, etc.), return "FizzBuzz".
// Examples
// fizzBuzz(3) == "Fizz"
// fizzBuzz(5) == "Buzz"
// fizzBuzz(15) == "FizzBuzz"
// fizzBuzz(4) == "4"
func fizzBuzz(n: Int) -> String {
if n % 3 == 0 && n % 5 == 0 {
return "FizzBuzz"
} else if n % 3 == 0 {
return "Fizz"
} else if n % 5 == 0 {
return "Buzz"
} else {
return String(UnicodeScalar(n + 65))
}
}
// 6. Create a function that takes a number as an argument.
// Returns the letter corresponding to that digit in the English alphabet: 0 = A, 1 = B, 2 = C, etc.
// However, for multiples of 4, return "Pling".
// For multiples of 6, return "Plang".
// For multiples of 8, return "Plong".
// For numbers which are multiples of both 3 and 5, return "FizzBuzz".
// For numbers which are multiples of both 4 and 6, return "PlingPlang".
// For numbers which are multiples of both 4 and 8, return "PlingPlong".
// For numbers which are multiples of both 6 and 8, return "PlangPlong".
// For numbers which are multiples of both 3 and 8, return "FizzPlong".
// For numbers which are multiples of both 3 and 6, return "FizzPlang".
// For numbers which are multiples of both 4 and 6, return "PlingPlang".
// For numbers which are multiples of both 4 and 8, return "PlingPlong".
// For numbers which are multiples of both 6 and 8, return "PlangPlong".
// For numbers which are multiples of both 3 and 8, return "F
return String(UnicodeScalar(n + 65)) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
return String(UnicodeScalar(n + 65)) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
func addTen(num: Int) -> Int {
return num + 10
}
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
return Int(x) == Int(y) + Int(z) || Int(y) == Int(x) + Int(z) || Int(z) == Int(x) + Int(y)
}
// 3. Create a function that takes a number as an argument.
// Add 10 to that number and return the result.
// Examples
// addTen(0) == 10
// addTen(9) == 19
// addTen(-8) == -2
func addTen(num: Int) -> Int {
return num + 10
}
// 4. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 5. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 6. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 7. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 8. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 9. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50) == 50
// lessThan100(100) == 100
func lessThan100(num: Int) -> Int {
return num < 100 ? num + 10 : num
}
// 10. Create a function that takes a number as an argument.
// Add 10 to that number if it's under 100.
// Otherwise, return the number as is.
// Examples
// lessThan100(20) == 30
// lessThan100(50
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
if char.isVowel {
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97
result += String(UnicodeScalar(index))
} else {
result += char
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased()
} else {
result += String(char).uppercased()
}
if char.isVowel {
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97
result += String(UnicodeScalar(index))
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97 // value of type 'Character' has no member 'unicodeScalarValue'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func encode(message: String) -> String {
let lowerCase = message.lowerCasedString
var result = ""
for letter in lowerCase {
if letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u" {
result += String(lowerCase.index(of: letter)!.next!.next!)
} else {
result += letter
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let lowerCase = message.lowerCasedString
var result = ""
for letter in lowerCase {
if letter == "a" || letter == "e" || letter == "i" || letter == "o" || letter == "u" {
result += String(lowerCase.index(of: letter)!.next!.next!)
} else {
result += letter
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let lowerCase = message.lowerCasedString // value of type 'String' has no member 'lowerCasedString'
func encode(message: String) -> String {
let result = ""
for char in message {
if char.isUpperCase {
result += String(char).lowercase
} else {
result += String(char).uppercase
}
if char.isVowel {
let index = (char.unicode.codePoint! + 2) % 26
result += String(UnicodeScalar(index))
} else {
result += String(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let result = ""
for char in message {
if char.isUpperCase {
result += String(char).lowercase
} else {
result += String(char).uppercase
}
if char.isVowel {
let index = (char.unicode.codePoint! + 2) % 26
result += String(UnicodeScalar(index))
} else {
result += String(char)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if char.isUpperCase { // value of type 'Character' has no member 'isUpperCase'
result += String(char).lowercase // value of type 'String' has no member 'lowercase'
result += String(char).uppercase // value of type 'String' has no member 'uppercase'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = (char.unicode.codePoint! + 2) % 26 // value of type 'Character' has no member 'unicode'
result += String(char) // left side of mutating operator isn't mutable: 'result' is a 'let' constant
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for letter in message {
if letter.isUpperCased {
result += letter.lowerCased
} else {
result += letter.upperCased
}
if vowels.contains(letter.lowerCased) {
let index = vowels.index(of: letter.lowerCased)!
let nextIndex = (index + 2) % 5
result += vowels[nextIndex]
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for letter in message {
if letter.isUpperCased {
result += letter.lowerCased
} else {
result += letter.upperCased
}
if vowels.contains(letter.lowerCased) {
let index = vowels.index(of: letter.lowerCased)!
let nextIndex = (index + 2) % 5
result += vowels[nextIndex]
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if letter.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
result += letter.lowerCased // value of type 'Character' has no member 'lowerCased'
result += letter.upperCased // value of type 'Character' has no member 'upperCased'
if vowels.contains(letter.lowerCased) { // value of type 'Character' has no member 'lowerCased'
let index = vowels.index(of: letter.lowerCased)! // value of type 'Character' has no member 'lowerCased'
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased
} else {
result += String(char).uppercased
}
if char.isVowel {
let index = String(char).lowercased.index(of: "aeiou")
let nextLetter = String(char).lowercased.index(after: index)
let nextLetter = String(char).lowercased.index(after: index)
result += String(char).lowercased.substring(nextLetter, length: 2)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased
} else {
result += String(char).uppercased
}
if char.isVowel {
let index = String(char).lowercased.index(of: "aeiou")
let nextLetter = String(char).lowercased.index(after: index)
let nextLetter = String(char).lowercased.index(after: index)
result += String(char).lowercased.substring(nextLetter, length: 2)
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
result += String(char).lowercased // function produces expected type 'String'; did you mean to call it with '()'?
result += String(char).uppercased // function produces expected type 'String'; did you mean to call it with '()'?
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = String(char).lowercased.index(of: "aeiou") // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
result += String(char).lowercased.substring(nextLetter, length: 2) // value of optional type 'String?' must be unwrapped to refer to member 'lowercased' of wrapped base type 'String'
result += String(char).lowercased.substring(nextLetter, length: 2) // no exact matches in call to initializer
result += String(char).lowercased.substring(nextLetter, length: 2) // value of type '(() -> String)?' has no member 'substring'
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased
} else {
result += String(char).uppercased
}
if char.isVowel {
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97
result += String(UnicodeScalar(index))
} else {
result += String(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char).lowercased
} else {
result += String(char).uppercased
}
if char.isVowel {
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97
result += String(UnicodeScalar(index))
} else {
result += String(char)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
result += String(char).lowercased // function produces expected type 'String'; did you mean to call it with '()'?
result += String(char).uppercased // function produces expected type 'String'; did you mean to call it with '()'?
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = (char.unicodeScalarValue - 97 + 2) % 26 + 97 // value of type 'Character' has no member 'unicodeScalarValue'
func encode(message: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in message {
if char.isLowercaseLetter {
let index = alphabet.firstIndex(of: char)!
let nextIndex = (index + 2) % alphabet.count
result += alphabet[nextIndex]
} else {
result += char
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
var result = ""
for char in message {
if char.isLowercaseLetter {
let index = alphabet.firstIndex(of: char)!
let nextIndex = (index + 2) % alphabet.count
result += alphabet[nextIndex]
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
if char.isLowercaseLetter { // value of type 'Character' has no member 'isLowercaseLetter'
let nextIndex = (index + 2) % alphabet.count // cannot convert value of type 'String.Index' to expected argument type 'Int'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char.lowerCased)
} else {
result += String(char.upperCased)
}
if char.isVowel {
let index = (CharacterSet.letters.rangeOfCharacter(in: String(char)).location + 2) % 26
result += String(Character(index + 65))
} else {
result += String(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCased {
result += String(char.lowerCased)
} else {
result += String(char.upperCased)
}
if char.isVowel {
let index = (CharacterSet.letters.rangeOfCharacter(in: String(char)).location + 2) % 26
result += String(Character(index + 65))
} else {
result += String(char)
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if char.isUpperCased { // value of type 'Character' has no member 'isUpperCased'
result += String(char.lowerCased) // value of type 'Character' has no member 'lowerCased'
result += String(char.upperCased) // value of type 'Character' has no member 'upperCased'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = (CharacterSet.letters.rangeOfCharacter(in: String(char)).location + 2) % 26 // value of type 'CharacterSet' has no member 'rangeOfCharacter'
result += String(Character(index + 65)) // cannot convert value of type 'Int' to expected argument type 'String'
result += String(Character(index + 65)) // no exact matches in call to initializer
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCase {
result += String(char).lowercaseString
} else {
result += String(char).uppercaseString
}
if char.isVowel {
let index = (CharacterSet.letters.rangeOfCharacters(in: String(char)).location + 2) % 26
result += String(characters: [UnicodeScalar(index + 65)], range: ...)
} else {
result += char
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isUpperCase {
result += String(char).lowercaseString
} else {
result += String(char).uppercaseString
}
if char.isVowel {
let index = (CharacterSet.letters.rangeOfCharacters(in: String(char)).location + 2) % 26
result += String(characters: [UnicodeScalar(index + 65)], range: ...)
} else {
result += char
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if char.isUpperCase { // value of type 'Character' has no member 'isUpperCase'
result += String(char).lowercaseString // value of type 'String' has no member 'lowercaseString'
result += String(char).uppercaseString // value of type 'String' has no member 'uppercaseString'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
let index = (CharacterSet.letters.rangeOfCharacters(in: String(char)).location + 2) % 26 // value of type 'CharacterSet' has no member 'rangeOfCharacters'
result += String(characters: [UnicodeScalar(index + 65)], range: ...) // cannot convert value of type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') to expected element type 'Character'
result += String(characters: [UnicodeScalar(index + 65)], range: ...) // extra argument 'range' in call
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isLowercaseLetter {
let index = (Character(char).asciiValue - 97 + 2) % 26
result += String(Character(Character(char).asciiValue + index))
} else {
result += String(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
if char.isLowercaseLetter {
let index = (Character(char).asciiValue - 97 + 2) % 26
result += String(Character(Character(char).asciiValue + index))
} else {
result += String(char)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------
if char.isLowercaseLetter { // value of type 'Character' has no member 'isLowercaseLetter'
let index = (Character(char).asciiValue - 97 + 2) % 26 // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
let index = (Character(char).asciiValue - 97 + 2) % 26 // missing argument label 'extendedGraphemeClusterLiteral:' in call
result += String(Character(Character(char).asciiValue + index)) // missing argument label 'extendedGraphemeClusterLiteral:' in call
result += String(Character(Character(char).asciiValue + index)) // cannot convert value of type 'UInt8?' to expected argument type 'String'
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
for j in 2..<i {
if i % j == 0 {
break
}
}
sum += i.digits.map { $0 == 1 ? 0 : 1 }.reduce(0, \+)
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
for j in 2..<i {
if i % j == 0 {
break
}
}
sum += i.digits.map { $0 == 1 ? 0 : 1 }.reduce(0, \+)
}
}
return sum
}
//}
//
//{
// let lst = [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 81, 12, 3, 1, 21]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}
//
//{
//
sum += i.digits.map { $0 == 1 ? 0 : 1 }.reduce(0, \+) // value of type 'Int' has no member 'digits'
sum += i.digits.map { $0 == 1 ? 0 : 1 }.reduce(0, \+) // expected expression path in Swift key path
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
sum += i.digits.map { $0.digit }.reduce(0, \+) // expected expression path in Swift key path
sum += i.digits.map { $0.digit }.reduce(0, \+) // value of type 'Int' has no member 'digits'
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
for j in 2...i {
if i % j == 0 {
break
}
}
if j == i {
sum += i
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
for j in 2...i {
if i % j == 0 {
break
}
}
if j == i {
sum += i
}
}
}
return sum
}
// Task 2
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
// Examples:
// skjkasdkd("abc123xyz") == 123
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 12+2!") == 14
// skjkasdkd("This is number 1! But is it?") == 1
// skjkasdkd("") == 0
// skjkas
if j == i { // cannot find 'j' in scope
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
func a_count(str: String) -> Int {
return str.count(.a)
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
// 10. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 11. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 12. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 13. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 14. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 15. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count("a") == 1
// a_count("") == 0
func a_count(str: String) -> Int {
return str.count(.a)
}
// 16. Write a function that takes a string and returns the number of times
// the letter “a” appears in it.
// Examples:
// a_count("Hello") == 1
// a_count("Hello, World!") == 2
// a_count("H3ll0, W0rld!") == 3
// a_count
sum += i.digits.map { $0.digit }.reduce(0, \+) // expected expression path in Swift key path
sum += i.digits.map { $0.digit }.reduce(0, \+) // value of type 'Int' has no member 'digits'
return str.count(.a) // cannot call value of non-function type 'Int'
return str.count(.a) // cannot infer contextual base in reference to member 'a'
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i.digits.map { $0.digit }.reduce(0, \+)
}
}
}
return sum
}
//}
//{
// let lst = [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]
// print(skjkasdkd(lst: lst))
//}
//{
// let lst = [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]
// print(skjkasdkd(lst: lst))
//}
//{
// let lst = [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]
// print(skjkasdkd(lst: lst))
//}
//{
// let lst = [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]
// print(skjkasdkd(lst: lst))
//}
//{
// let lst = [0, 81, 12, 3, 1, 21]
// print(skjkasdkd(lst: lst))
//}
//{
// let lst = [0, 8, 1, 2, 1, 7]
// print(skjkasdkd(lst: lst))
//}<|endoftext|>//{
// let lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
sum += i.digits.map { $0.digit }.reduce(0, \+) // expected expression path in Swift key path
sum += i.digits.map { $0.digit }.reduce(0, \+) // value of type 'Int' has no member 'digits'
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
sum += Int(String(i).characters.last!)!
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
sum += Int(String(i).characters.last!)!
}
}
return sum
}
// Task 2
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// Examples:
// skjkasdkd("abc123xyz") == 123
// skjkasdkd("aa11b33") == 44
// skjkasdkd("7 11") == 18
// skjkasdkd("Chocolate! 123") == 123
// skjkasdkd("5one") == 5
// skjkasdkd("1 2 3") == 6
// skjkasdkd("a 123$") == 123
// skjkasdkd("one two 3") == 3
// skjkasdkd("one 2 3") == 5
// skjkasdkd("one23") == 23
// skjkasdkd("one23 ") == 23
// skjkasdkd("one23!") == 23
// skjkasdkd("one!23") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd("one!23 ") == 23
// skjkasdkd
sum += Int(String(i).characters.last!)! // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i
}
}
}
return sum
}
// Task 2
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i
}
}
}
return sum
}
// Task 3
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) ==
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
var count = 0
for j in (1...i) {
if i % j == 0 {
count += 1
}
}
if count == 2 {
sum += i
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
var count = 0
for j in (1...i) {
if i % j == 0 {
count += 1
}
}
if count == 2 {
sum += i
}
}
}
return sum
}
// Task 2
// Write a function that takes a string as a parameter and returns a new string that contains all the vowels from the original string (without duplicates), in the order they appeared in the original string.
// The vowels are (a, e, i, o, u, and y).
// For example, if the string passed to your function is "There are 26 letters in the alphabet", then your function should return "eiea".
// Examples:
// skjkasdkd("There are 26 letters in the alphabet") == "eiea"
// skjkasdkd("The quick brown fox jumps over the lazy dog") == "eieaou"
// skjkasdkd("aeiou") == "aeiou"
// skjkasdkd("") == ""
// skjkasdkd("a") == "a"
// Task 3
// Write a function that takes a string as a parameter and returns a new string that contains all the vowels from the original string (without duplicates), in the order they appeared in the original string.
// The vowels are (a, e, i, o, u, and y).
// For example, if the string passed to your function is "There are 26 letters in the alphabet", then your function should return "eiea".
// Examples:
// skjkasdkd("There are 26 letters in the alphabet") == "eiea"
// skjkasdkd("The quick brown fox jumps over the lazy dog") == "eieaou"
// skjkasdkd("aeiou") == "aeiou"
// skjkasdkd("") == ""
// skjkasdkd("a") == "a"
// Task 4
// Write a function that takes a string as a parameter and returns a new string that contains all the vowels from the original string (without duplicates), in the order they appeared in the original string.
// The vowels are (a, e, i, o, u, and y).
// For example, if the string passed to your function is "There are 26 letters in the alphabet", then your function should return "eiea".
// Examples:
// skjkasdkd("There are 26 letters in the alphabet") == "eiea"
// skjkasdkd("The quick brown fox jumps over the lazy dog") == "eieaou"
// skjkasdkd("aeiou") == "aeiou"
// skjkasdkd("") == ""
// skjkasdkd("a") == "a"
// Task 5
// Write a function that takes a string as a parameter and returns a new string that contains all the vowels from the original string (without duplicates), in the order they appeared in the original string.
// The vowels are (a, e, i, o, u, and y).
// For example, if the string passed to your function is "There are 26 letters in the alphabet", then your function should return "eiea".
// Examples:
// skjkasdkd("There are 26 letters in the alphabet") == "eiea"
// skjkasdkd("The quick brown fox jumps over the lazy dog") == "eieaou"
// skjkasdkd("aeiou") == "aeiou"
// skjkasdkd("") == ""
// skjkasdkd("a") == "a"
// Task 6
// Write a function that takes a string as a parameter and returns a new string that contains all the vowels from the original string (without duplicates), in the order they appeared in the original string.
// The vowels are (a, e, i, o, u, and y).
// For example
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
var j = i
while j > 0 {
sum += j % 10
j /= 10
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 0 {
var j = i
while j > 0 {
sum += j % 10
j /= 10
}
}
}
return sum
}
// 2. Write a function that takes a string and returns the number of times each letter appears in the string.
// Examples:
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello") == {"H": 1, "e": 1, "l": 2, "o": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 1, "W": 1, "r": 1, "d": 1}
// countLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o":
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i
}
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i > 1 {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
sum += i
}
}
}
return sum
}
// Task 2
// You are given a string.
// You need to find the largest palindromic number in the string and return its length.
// Examples:
// skjkasdkd("abba") == 4
// skjkasdkd("abbaa") == 5
// skjkasdkd("abbaabba") == 8
// skjkasdkd("abbaabbaabba") == 10
// skjkasdkd("abbaabbaabbaabba") == 15
// skjkasdkd("abbaabbaabbaabbaabba") == 16
// skjkasdkd("abbaabbaabbaabbaabbaabba") == 20
// skjkasdkd("abbaabbaabbaabbaabbaabbaabba") == 25
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabba") == 30
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabba") == 35
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 40
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 45
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 50
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 55
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 60
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 65
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 70
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 75
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba") == 80
// skjkasdkd("abbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaab
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
print(countUpTo(10))
print(countUpTo(11))
print(countUpTo(0))
print(countUpTo(20))
print(countUpTo(1))
print(countUpTo(18))
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // missing argument label 'n:' in call
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
if n == 0 {
return []
}
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func starString(string: String) -> String {
if string.isEmpty {
return ""
}
var result = ""
for i in 0..<string.count {
if i == 0 {
result += "\(string[i])*"
} else if i == string.count - 1 {
result += "*\(string[i])"
} else {
result += "*\(string[i])*"
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
if n == 0 {
return []
}
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string as a parameter and returns a new string that contains "*"
// characters between each character.
// For example, if the string passed is "kata", the returned string should be "k*a*t*a".
// For example, if the string passed is "hello world", the returned string should be "h*e*l*l*o* *w*o*r*l*d".
// The returned string should have two characters between each of the characters of the original string.
// The first character should not have a * character between it and the * character should be a space.
// The last character should not have a * character between it and the * character should be a space.
// If the parameter is an empty string, return an empty string.
// Example:
// starString("kata") == "k*a*t*a"
// starString("hello world") == "h*e*l*l*o* *w*o*r*l*d"
// starString("") == ""
func starString(string: String) -> String {
if string.isEmpty {
return ""
}
var result = ""
for i in 0..<string.count {
if i == 0 {
result += "\(string[i])*"
} else if i == string.count - 1 {
result += "*\(string[i])"
} else {
result += "*\(string[i])*"
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string as a parameter and returns a new string that contains "*"
// characters between each character.
// For example, if the string passed is "kata", the returned string should be "k*a*t*a".
// For example, if the string passed is "hello world", the returned string should be "h*e*l*l*o* *w*o*r*l*d".
// The returned string should have two characters between each of the characters of the original string.
// The first character should not have a * character between it and the * character should be a space.
// The last character should not have a * character between it and the * character should be a space.
// If the parameter is an empty string, return an empty string.
// Example:
// starString("kata") == "k*a*t*a"
// starString("hello world") == "h*e*l*l*o* *w*o*r*l*d"
// starString("") == ""
func starString(string: String) -> String {
if string.isEmpty {
return ""
}
var result = ""
for i in 0..<string.count {
if i == 0 {
result += "\(string[i])*"
} else if i == string.count - 1 {
result += "*\(string[i])"
} else {
result += "*\(string[i])*"
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string as a parameter and returns a new string that contains "*"
// characters between each character.
// For example, if the string passed is "kata", the returned string should be "k*a*t*a".
// For example, if the string passed
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // cannot find 'isPrime' in scope
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
result += "\(string[i])*" // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += "*\(string[i])" // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += "*\(string[i])*" // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 && i != n {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 && i != n {
return false
}
}
return true
}
print(countUpTo(10))
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // missing argument label 'n:' in call
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // missing argument label 'n:' in call
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // missing argument label 'n:' in call
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
if n == 0 {
return []
}
if n == 1 {
return []
}
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
if n == 0 {
return []
}
if n == 1 {
return []
}
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 10. Write a function that takes a string as an argument and returns a new string that contains the same letters in the same order, but with each duplicate removed.
// for example:
// removeDuplicates("abcde") == "abcde"
// removeDuplicates("abcabc") == "abc"
// removeDuplicates("") == ""
// removeDuplicates("a") == "a"
// removeDuplicates("aa") == "a"
// removeDuplicates("aaa") == "a"
// removeDuplicates("ab") == "ab"
// removeDuplicates("abb") == "ab"
// removeDuplicates("abbb") == "ab"
// removeDuplicates("abbbb") == "ab"
// removeDuplicates("abbbbb") == "ab"
// removeDuplicates("abbbbbb") == "ab"
// removeDuplicates("abbbbbbb") == "ab"
// removeDuplicates("abbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab"
// removeDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") == "ab
if isPrime(i) { // cannot find 'isPrime' in scope
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Write a function that takes a non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Write a function that takes a non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Write a function that takes a non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Write a function that takes a non-negative integer and returns an array of the first
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // cannot find 'isPrime' in scope
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // cannot find 'isPrime' in scope
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = []
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(n: Int) -> Bool {
for i in 2...n {
if n % i == 0 {
return false
}
}
return true
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if isPrime(i) { // missing argument label 'n:' in call
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
if n == 0 {
return []
}
if n == 1 {
return []
}
if n == 2 {
return [2]
}
if n == 3 {
return [2, 3]
}
if n == 4 {
return [2, 3, 5]
}
if n == 5 {
return [2, 3, 5, 7]
}
if n == 6 {
return [2, 3, 5, 7, 11]
}
if n == 7 {
return [2, 3, 5, 7, 11, 13]
}
if n == 8 {
return [2, 3, 5, 7, 11, 13, 17]
}
if n == 9 {
return [2, 3, 5, 7, 11, 13, 17, 19]
}
if n == 10 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23]
}
if n == 11 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
}
if n == 12 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
}
if n == 13 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
}
if n == 14 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
}
if n == 15 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
}
if n == 16 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
}
if n == 17 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]
}
if n == 18 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]
}
if n == 19 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]
}
if n == 20 {
return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
}
if n == 21 {
return [2, 3, 5, 7, 11
XCTAssertTrue(countUpTo(n: 5) == [2, 3]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 6) == [2, 3, 5]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 7) == [2, 3, 5]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 10) == [2, 3, 5, 7]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 0) == [] as [Int]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 22) == [2, 3, 5, 7, 11, 13, 17, 19]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 1) == [] as [Int]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 47) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]) // cannot find 'countUpTo' in scope
XCTAssertTrue(countUpTo(n: 101) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]) // cannot find 'countUpTo' in scope
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(
XCTAssertTrue(multiply(a: 148, b: 412) == 16) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 19, b: 28) == 72) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 2020, b: 1851) == 0) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 14, b: -15) == 20) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 76, b: 67) == 42) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 17, b: 27) == 49) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 0, b: 1) == 0) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 0, b: 0) == 0) // cannot find 'multiply' in scope
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(String.init).map(
XCTAssertTrue(multiply(a: 148, b: 412) == 16) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 19, b: 28) == 72) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 2020, b: 1851) == 0) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 14, b: -15) == 20) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 76, b: 67) == 42) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 17, b: 27) == 49) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 0, b: 1) == 0) // cannot find 'multiply' in scope
XCTAssertTrue(multiply(a: 0, b: 0) == 0) // cannot find 'multiply' in scope
func multiply(a: Int, b: Int) -> Int {
let aStr = String(a)
let bStr = String(b)
let aDigits = aStr.map { $0 == "-" ? 0 : Int($0) }
let bDigits = bStr.map { $0 == "-" ? 0 : Int($0) }
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit)
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit)
return aProduct * bProduct
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let aStr = String(a)
let bStr = String(b)
let aDigits = aStr.map { $0 == "-" ? 0 : Int($0) }
let bDigits = bStr.map { $0 == "-" ? 0 : Int($0) }
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit)
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit)
return aProduct * bProduct
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
let aDigits = aStr.map { $0 == "-" ? 0 : Int($0) } // no exact matches in call to initializer
let bDigits = bStr.map { $0 == "-" ? 0 : Int($0) } // no exact matches in call to initializer
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // string interpolation can only appear inside a string literal
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'digit' in scope
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // expected type after '->'
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'acc' in scope
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // expected type before '->'
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'acc' in scope
let aProduct = aDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'digit' in scope
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'digit' in scope
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // expected type after '->'
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // string interpolation can only appear inside a string literal
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'digit' in scope
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'acc' in scope
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // expected type before '->'
let bProduct = bDigits.reduce(0, \(acc, digit) -> acc * digit) // cannot find 'acc' in scope
return aProduct * bProduct // cannot convert return expression of type 'Duration' to return type 'Int'
func multiply(a: Int, b: Int) -> Int {
return Int(a % 10) * Int(b % 10)
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(a % 10) * Int(b % 10)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let aDigit = a % 10
let bDigit = b % 10
return aDigit * bDigit
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let aDigit = a % 10
let bDigit = b % 10
return aDigit * bDigit
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let aStr = String(a)
let bStr = String(b)
let aDigit = aStr[aStr.count - 1]
let bDigit = bStr[bStr.count - 1]
return Int(aDigit) * Int(bDigit)
}
func solution(a: Int, b: Int) -> Int {
return a + b >= 20 ? 1 : 0
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let aStr = String(a)
let bStr = String(b)
let aDigit = aStr[aStr.count - 1]
let bDigit = bStr[bStr.count - 1]
return Int(aDigit) * Int(bDigit)
}
// 2.
// Complete the function that takes two integers and returns 0 if the sum is 20 or more,
// 1 otherwise.
// Examples:
// solution(34, 4) == 0
// solution(50, 5) == 1
func solution(a: Int, b: Int) -> Int {
return a + b >= 20 ? 1 : 0
}
// 3.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 4.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 5.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 6.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 7.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 8.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 9.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 10.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { $0 + $1 })
}
// 11.
// Complete the function that takes an array of integers as input, and returns the
// sum of all the integers in the array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([
let aDigit = aStr[aStr.count - 1] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
let bDigit = bStr[bStr.count - 1] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return Int(aDigit) * Int(bDigit) // no exact matches in call to initializer
return Int(aDigit) * Int(bDigit) // no exact matches in call to initializer
func multiply(a: Int, b: Int) -> Int {
let aDigit = a % 10
let bDigit = b % 10
return aDigit * bDigit
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let aDigit = a % 10
let bDigit = b % 10
return aDigit * bDigit
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(String.init).joined())
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(String.init).joined())
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
return Int(String(a...b).map(String.init).joined()) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(String(a...b).map(String.init).joined()) // no exact matches in call to initializer
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String.init).joined())!
}
}
struct Solution {
static func multiply(a: Int, b: Int) -> Int {
return Int(String(a...b).map(Character.init).map(String
return Int(String(a...b).map(Character.init).map(String.init).joined())! // no exact matches in call to initializer
return Int(String(a...b).map(Character.init).map(String.init).joined())! // no exact matches in call to initializer
func multiply(a: Int, b: Int) -> Int {
return Int(String(a.toString().last!) + String(b.toString().last!))!
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
return Int(String(a.toString().last!) + String(b.toString().last!))!
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 2. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 6. Given a string s, return the sum of the number of vowels in each word of s.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 2.
// Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "why not") == 1
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 3.
// Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "why not") == 1
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 4.
// Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "why not") == 1
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 5.
// Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 0
// countVowels(s: "why not") == 1
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 6.
// Given a string s, return the sum of the number of vowels in each word of s.
// For example:
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func sumNumbers(s: String) -> Int {
var sum = 0
var number = ""
for char in s {
if char.isDigit(char:){
number += String(char)
} else {
if number != "" {
sum += Int(number)
number = ""
}
}
}
if number != "" {
sum += Int(number)
}
return sum
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 10. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// sumNumbers(s: "abc123xyz") == 123
// sumNumbers(s: "aa11b33") == 44
// sumNumbers(s: "7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var number = ""
for char in s {
if char.isDigit(char:){
number += String(char)
} else {
if number != "" {
sum += Int(number)
number = ""
}
}
}
if number != "" {
sum += Int(number)
}
return sum
}
// -----------------------------------------------------------------------------
// 11. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// sumNumbers(s: "abc123xyz") == 123
// sumNumbers(s: "aa11b33") == 44
// sumNumbers(s: "7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var number = ""
for char in s {
if char.isDigit(char:){
number += String(char)
} else {
if number != "" {
sum += Int(number)
number = ""
}
}
}
if number != "" {
sum += Int(number)
}
return sum
}
// -----------------------------------------------------------------------------
// 12. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// sumNumbers(s: "abc123xyz") == 123
// sumNumbers(s: "aa11b33") == 44
// sumNumbers(s: "7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var number = ""
for char in s {
if char.isDigit(char:){
number += String(char)
} else {
if number != "" {
sum += Int(number)
number = ""
}
}
}
if number != "" {
sum += Int(number)
}
return sum
}
// -----------------------------------------------------------------------------
// 13. Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if char.isDigit(char:){ // value of type 'Character' has no member 'isDigit(char:)'
sum += Int(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
sum += Int(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper() {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isVowel() {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper() {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 10. Given a string s, return the sum of the number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') in every substring of s.
// If there are no vowels in s, return 0.
// For example:
// countVowels(s: "abc123") == 5
// countVowels(s: "1") == 0
// countVowels(s: "abec") == 3
// countVowels(s: "") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isVowel() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Given a string s, return the sum of the number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') in every substring of s.
// If there are no vowels in s, return 0.
// For example:
// countVowels(s: "abc123") == 5
// countVowels(s: "1") == 0
// countVowels(s: "abec") == 3
// countVowels(s: "") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isVowel() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. Given a string s, return the sum of the number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') in every substring of s.
// If there are no vowels in s, return 0.
// For example:
// countVowels(s: "abc123") == 5
// countVowels(s: "1") == 0
// countVowels(s: "abec") == 3
// countVowels(s: "") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isVowel() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Given a string s, return the sum of the number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') in every substring of s.
// If there are no vowels in s, return 0.
// For example:
// countVowels(s: "abc123") == 5
// countVowels(s: "1") == 0
// countVowels(s: "abec") == 3
// countVowels(s: "") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in
if s[i].isUpper() { // value of type 'Character' has no member 'isUpper'
if s[i].isVowel() { // value of type 'Character' has no member 'isVowel'
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 10. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 2
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 2
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 2
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Given a string s, return the sum of the number of vowels in each word of s.
// For example:
// countVowels(s: "aeiou") == 5
// countVowels(s: "why") == 2
// countVowels(s: "AEIOUaeiou") == 10
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 14. Given a string s, return the sum of the number of vowels in
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
func sumUpper(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isUpper {
sum += s[i].asciiValue
}
}
return sum
}
func sumLower(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isLower {
sum += s[i].asciiValue
}
}
return sum
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// 2. Write a function that takes a string as input and returns the sum of the uppercase letters and lowercase letters.
// Assume only letters (a-z, A-Z).
// countLetters(s: "abcDeF") == 6
// countLetters(s: "ABCDEF") == 6
// countLetters(s: "12345") == 0
// countLetters(s: "") == 0
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
// 3. Write a function that takes a string as input and returns the sum of the ASCII values of the uppercase letters.
// Assume only letters (a-z, A-Z).
// sumUpper(s: "abcDeF") == 163
// sumUpper(s: "ABCDEF") == 163
// sumUpper(s: "12345") == 0
// sumUpper(s: "") == 0
func sumUpper(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isUpper {
sum += s[i].asciiValue
}
}
return sum
}
// 4. Write a function that takes a string as input and returns the sum of the ASCII values of the lowercase letters.
// Assume only letters (a-z, A-Z).
// sumLower(s: "abcDeF") == 198
// sumLower(s: "ABCDEF") == 198
// sumLower(s: "12345") == 0
// sumLower(s: "") == 0
func sumLower(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isLower {
sum += s[i].asciiValue
}
}
return sum
}
// 5. Write a function that takes a string as input and returns the sum of the ASCII values of the uppercase letters.
// Assume only letters (a-z, A-Z).
// sumUpper(s: "abcDeF") == 163
// sumUpper(s: "ABCDEF") == 163
// sumUpper(s: "12345") == 0
// sumUpper(s: "") == 0
func sumUpper(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isUpper {
sum += s[i].asciiValue
}
}
return sum
}
// 6. Write a function that takes a string as input and returns the sum of the ASCII values of the lowercase letters.
// Assume only letters (a-z, A-Z).
// sumLower(s: "abcDeF") == 198
// sumLower(s: "ABCDEF") == 198
// sumLower(s: "12345") == 0
// sumLower(s: "") == 0
func sumLower(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i].isLower {
sum += s[i].asciiValue
}
}
return sum
}
// 7. Write a function that takes a string as input and returns the sum
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i].isUpper { // value of type 'Character' has no member 'isUpper'
} else if s[i].isLower { // value of type 'Character' has no member 'isLower'
if s[i].isUpper { // value of type 'Character' has no member 'isUpper'
sum += s[i].asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
if s[i].isLower { // value of type 'Character' has no member 'isLower'
sum += s[i].asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == " " {
count += 1
}
}
return count + 1
}
func countChars(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isLetter {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// 2. Write a function that takes a string as input and returns the sum of the uppercase letters and lowercase letters.
// Assume only the letters a-z and A-Z are in the string.
// countLetters(s: "abcdeF") == 12
// countLetters(s: "ABcdeF") == 15
// countLetters(s: "ABcdeF123") == 15
// countLetters(s: "ABcdeF123!@€£#") == 15
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
// 3. Write a function that takes a string as input and returns the number of vowels in the string.
// Assume only the letters a-z are in the string.
// countVowels(s: "aeiou") == 5
// countVowels(s: "bcdfghjklmnpqrstvwxyz") == 0
// countVowels(s: "") == 0
// countVowels(s: "aeiou5") == 5
// countVowels(s: "aeiou5bcdfghjklmnpqrstvwxyz") == 5
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// 4. Write a function that takes a string as input and returns the number of words in the string.
// Assume a word is a sequence of non-whitespace characters.
// countWords(s: "Hello world") == 2
// countWords(s: "One two three") == 3
// countWords(s: "") == 0
// countWords(s: "Hello world!") == 2
// countWords(s: "Hello world! One two three") == 4
func countWords(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == " " {
count += 1
}
}
return count + 1
}
// 5. Write a function that takes a string as input and returns the number of non-whitespace characters in the string.
// Assume only the letters a-z and A-Z are in the string.
// countChars(s: "Hello world") == 11
// countChars(s: "One two three") == 10
// countChars(s: "") == 0
// countChars(s: "Hello world!") == 11
// countChars(s: "Hello world! One two three") == 17
func countChars(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isLetter {
count += 1
}
}
return count
}
// 6. Write a function that takes a string as input and returns the number of non-whitespace characters in the string.
// Assume only the letters a-z and A-Z are in the string.
// countChars(s: "Hello world") == 11
// countChars(s: "
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i].isUpper { // value of type 'Character' has no member 'isUpper'
} else if s[i].isLower { // value of type 'Character' has no member 'isLower'
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == " " { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i].isLetter { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func findOdd(A: [Int]) -> Int {
var count = 0
var result = 0
for i in A {
for j in A {
if i == j {
count += 1
}
}
if count % 2 != 0 {
result = i
}
count = 0
}
return result
}
func firstNonRepeatedChar(s: String) -> String {
var result = ""
var count = 0
for i in s {
for j in s {
if i == j {
count += 1
}
}
if count == 1 {
result = String(i)
}
count = 0
}
return result
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Given an array of integers, find the one that appears an odd number of
// times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which
// is odd).
func findOdd(A: [Int]) -> Int {
var count = 0
var result = 0
for i in A {
for j in A {
if i == j {
count += 1
}
}
if count % 2 != 0 {
result = i
}
count = 0
}
return result
}
// -----------------------------------------------------------------------------
// 12. Given a string, return the first character that is not repeated
// anywhere in the string.
// For example, given the input 'abacabad', the output should be 'c', since
// the character at index 6 (the last occurence of 'c') is the first
// character that is not repeated anywhere in the string.
// Given the input 'abacabaabacaba', the output should be 'c', since
// there are two characters 'c' in the string, but they are both part of a
// larger substring that is repeated 4 times.
// Given the input 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', the output should be 'c', since there are no characters that are not repeated.
// Given the input 'abcdefghijklmnopqrstuvwxyz', the output should be 'a', since
// all of the characters are repeated.
func firstNonRepeatedChar(s: String) -> String {
var result = ""
var count = 0
for i in s {
for j in s {
if i == j {
count += 1
}
}
if count == 1 {
result = String(i)
}
count = 0
}
return result
}
// -----------------------------------------------------------------------------
// 13. Given a string, find the first character that is not repeated anywhere
// in the string.
// For example, given the input 'abacaba', the output should be 'c'.
// Given the input 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', the output should be 'c', since all characters occur more than once.
// Given the input 'abcdefghijklmnopqrstuvwxyz', the output should be 'a', since
// all characters occur only once and there are no repeating groups of
// characters (i.e. 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').
func firstNonRepeatedChar2
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// 2. Write a function that takes a string as input and returns the sum of the uppercase letters and lowercase letters.
// For example:
// countLetters(s: "abcDeF") == 6
// countLetters(s: "ABCDEF") == 6
// countLetters(s: "abcdeF") == 6
// countLetters(s: "12345") == 0
// countLetters(s: "") == 0
func countLetters(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i].isUpper {
count += 1
} else if s[i].isLower {
count += 1
}
}
return count
}
// 3. Write a function that takes a string as input and returns the number of words in the string.
// A word is defined as a sequence of non-whitespace characters. The test will not consider
// any characters other than letters, whitespace, and punctuation.
// For example:
// countWords(s: "Hello world") == 2
// countWords(s: "Hello world!") == 2
// countWords(s: "Hello world!!!") == 2
// countWords(s: "Hello world!!!!!") == 2
// countWords(s: "Hello world!!!!!!!") == 2
// countWords(s: "Hello world!!!!!!!!") == 2
// countWords(s: "Hello world!!!!!!!!!") == 2
// countWords(s: "Hello world!!!!!!!!!!") == 2
// countWords(s: "") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " ") == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " == 0
// countWords(s: " " ==
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i].isUpper { // value of type 'Character' has no member 'isUpper'
} else if s[i].isLower { // value of type 'Character' has no member 'isLower'
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func sumUp(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
sum += s[i].asciiValue
}
}
return sum
}
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
func countLower(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
// 2. Write a function that takes a string as input and returns the sum of the uppercase letters in the string.
// For example:
// sumUp(s: "aBCdEf") == 5
// sumUp(s: "abcdefg") == 0
// sumUp(s: "dBBE") == 0
func sumUp(s: String) -> Int {
var sum = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
sum += s[i].asciiValue
}
}
return sum
}
// 3. Write a function that takes a string as input and returns the number of vowels in the string.
// For example:
// countVowels(s: "aBCdEf") == 3
// countVowels(s: "abcdefg") == 0
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// 4. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" {
count += 1
}
}
return count
}
// 5. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// For example:
// countLower(s: "aBCdEf") == 8
// countLower(s: "abcdefg") == 0
// countLower(s: "dBBE") == 0
func countLower(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" {
count += 1
}
}
return count
}
// 6. Write a function that takes a string as input and returns the number of digits in the string.
// For example:
// countDigits(s: "aBCdEf") == 0
// countDigits(s: "abcdefg") == 0
// countDigits(s: "dBBE") == 0
func countDigits(s: String) -> Int {
var count = 0
for i in 0..<s.count {
if s[i] == "0" || s[i] == "1" || s[i] == "2" || s[i] == "3" || s[i] == "4" || s[i] == "5" || s[i] == "6" || s[i] == "7" || s[i]
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sum += s[i].asciiValue // cannot convert value of type 'UInt8?' to expected argument type 'Int'
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "A" || s[i] == "E" || s[i] == "I" || s[i] == "O" || s[i] == "U" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == "a" || s[i] == "e" || s[i] == "i" || s[i] == "o" || s[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
let abs2 = abs(number + 1)
if abs1 < abs2 {
return number - 1
} else {
return number + 1
}
}
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
let abs2 = abs(number + 1)
if abs1 < abs2 {
return number - 1
} else {
return number + 1
}
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH"
// firstLast("Z") == "Z"
func firstLast(string: String) -> String {
let first = string.first!
let last = string.last!
return string.replacingFirst(with: last).replacingLast(with: first)
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// firstLast("Hello") == "elH
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs1 = abs(number - 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(number + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number - 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return string.replacingFirst(with: last).replacingLast(with: first) // value of type 'String' has no member 'replacingFirst'
func closestInteger(value: String) -> Int {
let num = Int(value)
let abs = abs(num)
let abs1 = abs(num + 1)
if abs1 - abs < abs - 1 {
return num + 1
} else {
return num
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Int(value)
let abs = abs(num)
let abs1 = abs(num + 1)
if abs1 - abs < abs - 1 {
return num + 1
} else {
return num
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
let abs = abs(num) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs1 = abs(num + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if abs1 - abs < abs - 1 { // binary operator '<' cannot be applied to operands of type 'Duration' and 'Int'
if abs1 - abs < abs - 1 { // binary operator '-' cannot be applied to two 'Int' operands
return num + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return num // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number + 1)
return abs < abs2 ? number : number + 1
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number + 1)
return abs < abs2 ? number : number + 1
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(number + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return abs < abs2 ? number : number + 1 // cannot convert return expression of type 'Int?' to return type 'Int'
return abs < abs2 ? number : number + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let num = Int(value)
let abs = abs(num)
let abs2 = abs(num + 1)
if abs > abs2 {
return num + 1
} else {
return num
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Int(value)
let abs = abs(num)
let abs2 = abs(num + 1)
if abs > abs2 {
return num + 1
} else {
return num
}
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let abs = abs(num) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(num + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return num + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return num // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
if abs1 < abs {
return number - 1
} else {
return number
}
}
func inc(number: Int) -> Int {
return number + 1
}
func number_to_string(step: Int) -> String {
return "STEP \(step)"
}
func sum(number: Int) -> Int {
if number < 0 {
return -1
} else {
var sum = 0
for i in 1...number {
sum += i
}
return sum
}
}
func opposite(number: Int) -> Int {
return -number
}
func nextNumber(number: Int) -> Int {
return number + 1
}
func lessThan100(number1: Int, number2: Int) -> Bool {
return number1 + number2 < 100
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
if abs1 < abs {
return number - 1
} else {
return number
}
}
// 2. Create a function that takes a number as an argument, increments the number
// by +1 and returns the result.
// Examples
// inc(0) == 1
// inc(4) == 5
// inc(-3) == -2
func inc(number: Int) -> Int {
return number + 1
}
// 3. Create a function that takes a number (step) as an argument and returns the
// string as seen in the examples.
// Examples
// number_to_string(1) == "STEP 1"
// number_to_string(5) == "STEP 5"
// number_to_string(100) == "STEP 100"
func number_to_string(step: Int) -> String {
return "STEP \(step)"
}
// 4. Given a number, find the sum of all numbers between 1 and the number
// (including number).
// If the number is negative, return -1.
// Examples
// sum(3) == 6
// sum(5) == 15
// sum(-8) == -1
func sum(number: Int) -> Int {
if number < 0 {
return -1
} else {
var sum = 0
for i in 1...number {
sum += i
}
return sum
}
}
// 5. Given a number, find its opposite.
// Examples
// opposite(1) == -1
// opposite(-3) == 3
// opposite(0) == 0
func opposite(number: Int) -> Int {
return -number
}
// 6. Create a function that takes a number as an argument, increments the number
// (by default by one), and returns the result.
// Examples
// nextNumber(0) == 1
// nextNumber(9) == 10
// nextNumber(-3) == -2
// nextNumber(3) == 4
func nextNumber(number: Int) -> Int {
return number + 1
}
// 7. Create a function that takes a number as an argument, increments the number
// (by default by one), and returns the result.
// Examples
// nextNumber(0) == 1
// nextNumber(9) == 10
// nextNumber(-3) == -2
// nextNumber(3) == 4
func nextNumber(number: Int) -> Int {
return number + 1
}
// 8. Create a function that takes a number as an argument, increments the number
// (by default by one), and returns the result.
// Examples
// nextNumber(0) == 1
// nextNumber(9) == 10
// nextNumber(-3) == -2
// nextNumber(3) == 4
func nextNumber(number: Int) -> Int {
return number + 1
}
// 9. Create a function that takes a number as an argument, increments the number
// (by default by one), and returns the result.
// Examples
// nextNumber(0) == 1
// nextNumber(9) == 10
// nextNumber(-3) == -2
// nextNumber(3) == 4
func nextNumber(number: Int) -> Int {
return number + 1
}
// 10. Given two numbers, return true if the sum of both numbers is less than 100.
// Otherwise return false.
// Examples
// lessThan100(22, 15) == true
// lessThan100(83, 34) == false
// lessThan100(3, 77) == false
func lessThan100(number1: Int, number2: Int) -> Bool {
return number1 + number2 < 100
}
// 11. Given a non-empty array, return true if the value "7" appears in the array
// exactly 3 times, and no "7" appears anywhere else in the array.
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs1 = abs(number - 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number - 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number - 1)
if abs > abs2 {
return number - 1
} else {
return number
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number - 1)
if abs > abs2 {
return number - 1
} else {
return number
}
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra")
// // => "brcrdbr"
// removeVowels("")
// // => ""
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with
// all the vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// // => " hv nvr sn thn
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(number - 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number - 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number + 1)
if abs == abs2 {
return number
}
return number + (abs > abs2 ? 1 : 0)
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs2 = abs(number + 1)
if abs == abs2 {
return number
}
return number + (abs > abs2 ? 1 : 0)
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with
// all vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " prtr"
// removeVowels("hello world") == "hll wrd"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("ho ho ho") == "h h h"
// removeVowels("aaaaa") == ""
// removeVowels("uwu uwu") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with
// all vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " prtr"
// removeVowels("hello world") == "hll wrd"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("ho ho ho") == "h h h"
// removeVowels("aaaaa") == ""
// removeVowels("uwu uwu") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with
// all vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("pear tree") == " prtr"
// removeVowels("hello world") == "hll wrd"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("AEIOU") == ""
// removeVowels("ho ho ho") == "h h h"
// removeVowels("aaaaa") == ""
// removeVowels("uwu uwu") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with
// all vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(number + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number + (abs > abs2 ? 1 : 0) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
let abs2 = abs(number + 1)
if abs1 < abs2 {
return number - 1
} else {
return number + 1
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let abs1 = abs(number - 1)
let abs2 = abs(number + 1)
if abs1 < abs2 {
return number - 1
} else {
return number + 1
}
}
// -----------------------------------------------------------------------------
// 10. Create a function that takes a number (step) as an argument and returns
// the number of matchsticks in that step. See step 13's examples for a
// visual.
// Examples
// matchSticks(1) ➞ 6
// matchSticks(3) ➞ 21
// matchSticks(5) ➞ 219
// matchSticks(0) ➞ 1
// Notes
// There exists a closed form solution to this problem (look at step 13).
// You're not expected to solve this problem.
// If you're stuck, look at the Resources tab.
// If you're still stuck, ask the user to try to solve it on their own.
// Make sure to return the result as an integer.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 11. Create a function that takes a number (step) as an argument and returns
// the number of matchsticks in that step. See step 13's examples for a
// visual.
// Examples
// matchSticks(1) ➞ 6
// matchSticks(3) ➞ 21
// matchSticks(5) ➞ 219
// matchSticks(0) ➞ 1
// Notes
// There exists a closed form solution to this problem (look at step 13).
// You're not expected to solve this problem.
// If you're stuck, look at the Resources tab.
// If you're still stuck, ask the user to try to solve it on their own.
// Make sure to return the result as an integer.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 12. Create a function that takes a number (step) as an argument and returns
// the number of matchsticks in that step. See step 13's examples for a
// visual.
// Examples
// matchSticks(1) ➞ 6
// matchSticks(3) ➞ 21
// matchSticks(5) ➞ 219
// matchSticks(0) ➞ 1
// Notes
// There exists a closed form solution to this problem (look at step 13).
// You're not expected to solve this problem.
// If you're stuck, look at the Resources tab.
// If you're still stuck, ask the user to try to solve it on their own.
// Make sure to return the result as an integer.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 13. Create a function that takes a number (step) as an argument and returns
// the number of matchsticks in that step. See step 13's examples for a
// visual.
// Examples
// matchSticks(1) ➞ 6
// matchSticks(3) ➞ 21
// matchSticks(5) ➞ 219
// matchSticks(0) ➞ 1
// Notes
// There exists a closed form solution to this problem (look at step 13).
// You're not expected to solve this problem.
// If you're stuck, look at the Resources tab.
// If you're still stuck, ask the user to
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs1 = abs(number - 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let abs2 = abs(number + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number - 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let absDiff = abs(abs(number) - abs(abs(number) - 1))
if absDiff == 0 {
return number
}
if absDiff < abs(abs(number) - 1) {
return number - 1
}
return number
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let number = Int(value)
let abs = abs(number)
let absDiff = abs(abs(number) - abs(abs(number) - 1))
if absDiff == 0 {
return number
}
if absDiff < abs(abs(number) - 1) {
return number - 1
}
return number
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
let abs = abs(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number - 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return number // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func closestInteger(value: String) -> Int {
let num = Int(value)
let diff1 = abs(num - 2 * num)
let diff2 = abs(num - 2 * num + 1)
return num - diff1 < num - diff2 ? num - diff1 : num - diff2
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Int(value)
let diff1 = abs(num - 2 * num)
let diff2 = abs(num - 2 * num + 1)
return num - diff1 < num - diff2 ? num - diff1 : num - diff2
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
let diff1 = abs(num - 2 * num) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let diff1 = abs(num - 2 * num) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let diff2 = abs(num - 2 * num + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let diff2 = abs(num - 2 * num + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return num - diff1 < num - diff2 ? num - diff1 : num - diff2 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return num - diff1 < num - diff2 ? num - diff1 : num - diff2 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
func countOdds(n: Int) -> Int {
return (n * (n + 1) / 2)
}
func countPalindromes(s: String) -> Int {
var result = 0
for i in 0..<s.count {
for j in i..<s.count {
let substring = s[i..<j]
if substring == substring.reversed() {
result += 1
}
}
}
return result
}
func countGoodPairs(nums: [Int]) -> Int {
var result = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if i != j && nums[i] == nums[j] {
result += 1
}
}
}
return result
}
func countGoodPairs(nums: [Int]) -> Int {
var result = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j && nums[i] == nums[j] {
result += 1
}
}
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a positive integer n, return the number of odd-length subarrays of
// n.
// Examples:
// countOdds(n: 1) == 1
// countOdds(n: 2) == 3
// countOdds(n: 27) == 155
func countOdds(n: Int) -> Int {
return (n * (n + 1) / 2)
}
// -----------------------------------------------------------------------------
// 3. Given a string s, return the number of palindromic substrings in it.
// A string is a palindrome when it reads the same backward as forward.
// A substring is a contiguous sequence of characters within a string.
// Examples:
// countPalindromes(s: "abc") == 3
// countPalindromes(s: "aaa") == 6
// countPalindromes(s: "abacab") == 7
func countPalindromes(s: String) -> Int {
var result = 0
for i in 0..<s.count {
for j in i..<s.count {
let substring = s[i..<j]
if substring == substring.reversed() {
result += 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Examples:
// countGoodPairs(nums: [1, 2, 3, 1, 1, 3]) == 4
// countGoodPairs(nums: [1, 1, 1, 1]) == 6
// countGoodPairs(nums: [1, 2, 3]) == 0
func countGoodPairs(nums: [Int]) -> Int {
var result = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if i != j && nums[i] == nums[j] {
result += 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Examples:
// countGoodPairs(nums: [1, 2, 3, 1, 1, 3]) == 4
// countGoodPairs(nums: [1, 1, 1, 1]) == 6
// countGoodPairs(nums: [1, 2, 3]) == 0
func countGoodPairs(nums: [Int]) -> Int {
var result = 0
for i in 0..<nums.count {
for j in 0..<nums.count {
if i != j && nums[i] == nums[j] {
result += 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Examples:
// countGoodP
let substring = s[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if substring == substring.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func countGoodPairs(nums: [Int]) -> Int { // invalid redeclaration of 'countGoodPairs(nums:)'
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
for i in 1..<n {
if n % 2 == 0 {
result.append(n + 2 * i)
} else {
result.append(n + 2 * i - 1)
}
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
for i in 1..<n {
if n % 2 == 0 {
result.append(n + 2 * i)
} else {
result.append(n + 2 * i - 1)
}
}
return result
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
//------------------------------------
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as an argument and returns a string
// with the first and last characters swapped.
// Examples:
// swapFirstLast("Hello") == "oHell"
// swapFirstLast("Goodbye") == "yobdooG"
// swapFirstLast("") == ""
// swapFirstLast("a") == "a"
// swapFirstLast("aa") == "aa"
// swapFirstLast("ab") == "ba"
// swapFirstLast("abc") == "cba"
// swapFirstLast("abcd") == "dcba"
// swapFirstLast("abcde") == "edcba"
// swapFirstLast("abcdef") == "fecdba"
// swapFirstLast("abcdefg") == "gfedcba"
// swapFirstLast("abcdefgh") == "hgfecdba"
// swapFirstLast("abcdefghi") == "ihgfecdba"
// swapFirstLast("abcdefghij") == "jihgfecdba"
// swapFirstLast("abcdefghijk") == "kjihgfecdba"
// swapFirstLast("abcdefghijkl") == "lkjihgfecdba"
// swapFirstLast("abcdefghijklm") == "mkljihgfecdba"
// swapFirstLast("abcdefghijklmn") == "nmkljihgfecdba"
// swapFirstLast("abcdefghijklmno") == "nopkljihgfecdba"
// swapFirstLast("abcdefghijklmnop") == "opkljihgfecdba"
// swapFirstLast("abcdefghijklmnopq") == "pqkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqr") == "rqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrst") == "stqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstu") == "utqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuv") == "vutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvw") == "wvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwx") == "xvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxy") == "yvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba"
// swapFirstLast("abcdefghijklmnopqrstuvwxyz") == "yzvutqpkljihgfecdba
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
// -----------------------------------------------------------------------------
// 2. Given a positive integer n, return the number of all possible piles of stones
// that can be formed from n stones.
// Examples:
// pileOfStones(n: 1) == 1
// pileOfStones(n: 2) == 2
// pileOfStones(n: 3) == 2
// pileOfStones(n: 4) == 3
// pileOfStones(n: 5) == 3
// pileOfStones(n: 6) == 3
// pileOfStones(n: 7) == 4
// pileOfStones(n: 8) == 4
// pileOfStones(n: 9) == 4
// pileOfStones(n: 10) == 5
// pileOfStones(n: 11) == 5
// pileOfStones(n: 12) == 5
// pileOfStones(n: 13) == 6
// pileOfStones(n: 14) == 6
// pileOfStones(n: 15) == 6
// pileOfStones(n: 16) == 7
// pileOfStones(n: 17) == 7
// pileOfStones(n: 18) == 7
// pileOfStones(n: 19) == 8
// pileOfStones(n: 20) == 8
// pileOfStones(n: 21) == 8
// pileOfStones(n: 22) == 9
// pileOfStones(n: 23) == 9
// pileOfStones(n: 24) == 9
// pileOfStones(n: 25) == 10
// pileOfStones(n: 26) == 10
// pileOfStones(n: 27) == 10
// pileOfStones(n: 28) == 10
// pileOfStones(n: 29) == 11
// pileOfStones(n: 30) == 11
// pileOfStones(n: 31) == 11
// pileOfStones(n: 32) == 11
// pileOfStones(n: 33) == 12
// pileOfStones(n: 34) == 12
// pileOfStones(n: 35) == 12
// pileOfStones(n: 36) == 12
// pileOfStones(n: 37) == 13
// pileOfStones(n: 38) == 13
// pileOfStones(n: 39) == 13
// pileOfStones(n: 40) == 13
// pileOfStones(n: 41) == 14
// pileOfStones(n: 42) == 14
// pileOfStones(n: 43) == 14
// pileOfStones(n: 44) == 14
// pileOfStones(n: 45) == 15
// pileOfStones(n: 46) == 15
// pileOfStones(n: 47) == 15
// pileOfStones(n: 48) == 15
// pileOfStones(n: 49) == 16
// pileOfStones(n: 50) == 16
// pileOfStones(n: 51) == 16
// pileOfStones(n: 52) == 16
// pileOfStones(n: 53) == 17
// pileOfStones(n: 54) == 17
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
func firstMissingPositive(nums: [Int]) -> Int {
var missing = 1
while true {
if nums.contains(missing) {
missing += 1
} else {
return missing
}
}
}
func doubled(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given an array of integers, find the first missing positive integer in linear
// time and constant space. In other words, find the lowest positive integer that
// does not exist in the array. The array can contain duplicates and negative
// numbers as well.
// Examples:
// firstMissingPositive([1, 2, 0]) == 3
// firstMissingPositive([3, 4, -1, 1]) == 2
// firstMissingPositive([-8, -7, -6]) == 1
func firstMissingPositive(nums: [Int]) -> Int {
var missing = 1
while true {
if nums.contains(missing) {
missing += 1
} else {
return missing
}
}
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubled(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Given an array of integers, find the first missing positive integer in linear
// time and constant space. In other words, find the lowest positive integer that
// does not exist in the array. The array can contain duplicates and negative
// numbers as well.
// Examples:
// firstMissingPositive([1, 2, 0]) == 3
// firstMissingPositive([3, 4, -1, 1]) == 2
// firstMissingPositive([-8, -7, -6]) == 1
func firstMissingPositive(nums: [Int]) -> Int {
var missing = 1
while true {
if nums.contains(missing) {
missing += 1
} else {
return missing
}
}
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Given an array of integers, find the first missing positive integer in linear
// time and constant space. In other words, find the lowest positive integer that
// does not exist in the array. The array can contain duplicates and negative
// numbers as well.
// Examples:
// firstMissingPositive([1, 2, 0]) == 3
// firstMissingPositive([3, 4, -1, 1]) == 2
// firstMissingPositive([-8, -7, -6]) == 1
func firstMissingPositive(nums: [Int]) -> Int {
var missing = 1
while true {
if nums.contains(missing) {
missing += 1
} else {
return missing
}
}
}
// -----------------------------------------------------------------------------
// 1.5
// -----------------------------------------------------------------------------
// Given an array of integers,
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = 1
for _ in 1...n {
pile.append(current)
current += 2
}
return pile
}
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
var current = 1
for _ in 1...n {
pile.append(current)
current += 2
}
return pile
}
// -----------------------------------------------------------------------------
// 2. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 3. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 4. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 5. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 6. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 7. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(n: 3) == 5
// numberOfWays(n: 4) == 14
func numberOfWays(n: Int) -> Int {
var ways = 0
var current = 1
for _ in 1...n {
ways += current
current += 2
}
return ways
}
// -----------------------------------------------------------------------------
// 8. Given a positive integer n, return the number of ways to make a pile of n
// stones.
// Examples:
// numberOfWays(
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
pile.append(i * 2 - 1)
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
pile.append(i * 2 - 1)
}
return pile
}
// -----------------------------------------------------------------------------
// 1.2.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var pile = [Int]()
for i in 1...n {
if i % 2 == 0 {
pile.append(i * 2)
} else {
pile.append(i * 2 - 1)
}
}
return pile
}
// -----------------------------------------------------------------------------
// 1.10.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
return s.split(separator: ", ")
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ")
}
// -----------------------------------------------------------------------------
// 1.2.1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
return s.split(separator: ", ") // cannot convert return expression of type '[String.SubSequence]' (aka 'Array<Substring>') to return type '[String]'
func wordsString(s: String) -> [String] {
return s.split(separator: ", ")
}
func squareArray(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted()
}
func descendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: <)
}
func descendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: >)
}
func ascendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: <)
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ")
}
// -----------------------------------------------------------------------------
// 2. Given an array of numbers, return an array containing the squares of
// the numbers in ascending order.
// For example:
// squareArray(nums: [1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]
// squareArray(nums: [-5, -4, -3, -2, -1]) == [1, 4, 9, 16, 25]
// squareArray(nums: []) == []
func squareArray(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted()
}
// -----------------------------------------------------------------------------
// 3. Given an array of numbers, return an array containing the squares of
// the numbers in descending order.
// For example:
// descendingSquares(nums: [1, 2, 3, 4, 5]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: [-5, -4, -3, -2, -1]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: []) == []
func descendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: <)
}
// -----------------------------------------------------------------------------
// 4. Given an array of numbers, return an array containing the squares of
// the numbers in descending order.
// For example:
// descendingSquares(nums: [1, 2, 3, 4, 5]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: [-5, -4, -3, -2, -1]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: []) == []
func descendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: >)
}
// -----------------------------------------------------------------------------
// 5. Given an array of numbers, return an array containing the squares of
// the numbers in ascending order.
// For example:
// ascendingSquares(nums: [1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]
// ascendingSquares(nums: [-5, -4, -3, -2, -1]) == [1, 4, 9, 16, 25]
// ascendingSquares(nums: []) == []
func ascendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: <)
}
// -----------------------------------------------------------------------------
// 6. Given an array of numbers, return an array containing the squares of
// the numbers in descending order.
// For example:
// descendingSquares(nums: [1, 2, 3, 4, 5]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: [-5, -4, -3, -2, -1]) == [25, 16, 9, 4, 1]
// descendingSquares(nums: []) == []
func descendingSquares(nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted(by: >)
}
// ------
return s.split(separator: ", ") // cannot convert return expression of type '[String.SubSequence]' (aka 'Array<Substring>') to return type '[String]'
func descendingSquares(nums: [Int]) -> [Int] { // invalid redeclaration of 'descendingSquares(nums:)'
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels(s: "Hello world") == "Hll wrld"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return s.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// ---------------------------------------------------------------------
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return s.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func bitsCount(n: Int) -> Int {
return String(n, radix: 2).count(for: .one)
}
func sumDigits(n: Int) -> Int {
return String(abs(n)).map { $0.digitValue }.reduce(0, \+)
}
func trailingZeros(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// 2. Write a function that takes a string as input and returns the string reversed.
// For example:
// reverseString(s: "Hello") == "olleH"
// reverseString(s: "Greetings") == "gnirtseG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Write a function that takes an integer as input, and returns the number of
// bits that are equal to one in the binary representation of that number.
// You can guarantee that input is non-negative.
// Example: The binary representation of 1234 is 10011010010, so the function
// should return 5 in this case
// bitsCount(n: 1234) == 5
func bitsCount(n: Int) -> Int {
return String(n, radix: 2).count(for: .one)
}
// 4. Write a function that takes a number as input, and returns the sum of the
// digits that make up the number.
// For example:
// sumDigits(n: 1234) == 10
// sumDigits(n: 100) == 1
// sumDigits(n: -32) == 5
func sumDigits(n: Int) -> Int {
return String(abs(n)).map { $0.digitValue }.reduce(0, \+)
}
// 5. Write a function that takes a number as input, and returns the number of
// trailing zeros in the number's factorial.
// For example:
// trailingZeros(n: 3) == 0
// trailingZeros(n: 5) == 1
// trailingZeros(n: 10) == 2
// trailingZeros(n: 20) == 4
// trailingZeros(n: 30) == 7
func trailingZeros(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// 6. Write a function that takes a number as input, and returns the number of
// trailing zeros in the number's factorial.
// For example:
// trailingZeros(n: 3) == 0
// trailingZeros(n: 5) == 1
// trailingZeros(n: 10) == 2
// trailingZeros(n: 20) == 4
// trailingZeros(n: 30) == 7
func trailingZeros(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// 7. Write a function that takes a number as input, and returns the number of
// trailing zeros in the number's factorial.
// For example:
// trailingZeros(n: 3) == 0
// trailingZeros(n: 5) == 1
// trailingZeros(n: 10) == 2
// trailingZeros(n: 20) == 4
// trailingZeros(n: 30) == 7
func trailingZeros(n: Int) -> Int {
var count = 0
var i = 5
while n / i >= 1 {
count += n / i
i *= 5
}
return count
}
// 8. Write a function that takes a number as input, and returns the number of
// trailing zeros in the number's factorial.
// For example:
// trailingZeros(n: 3) == 0
// trailingZeros(n: 5) == 1
// trailingZeros(n: 10) == 2
// trailingZeros(n: 20) == 4
// trailingZeros(n: 30) == 7
func trailingZeros(n: Int) -> Int {
var count = 0
var i
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return String(n, radix: 2).count(for: .one) // cannot call value of non-function type 'Int'
return String(n, radix: 2).count(for: .one) // cannot infer contextual base in reference to member 'one'
return String(abs(n)).map { $0.digitValue }.reduce(0, \+) // missing argument for parameter #2 in call
return String(abs(n)).map { $0.digitValue }.reduce(0, \+) // expected expression path in Swift key path
return String(abs(n)).map { $0.digitValue }.reduce(0, \+) // value of type 'String.Element' (aka 'Character') has no member 'digitValue'
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func uppercaseString(s: String) -> String {
return s.uppercased()
}
func lowercaseString(s: String) -> String {
return s.lowercased()
}
func titleCaseString(s: String) -> String {
return String(s.capitalized)
}
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the string with
// all the letters in reverse order.
// For example:
// reverseString(s: "Hello world") == "dlrow olleH"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the string with
// all the letters in uppercase.
// For example:
// uppercaseString(s: "Hello world") == "HELLO WORLD"
func uppercaseString(s: String) -> String {
return s.uppercased()
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the string with
// all the letters in lowercase.
// For example:
// lowercaseString(s: "Hello world") == "hello world"
func lowercaseString(s: String) -> String {
return s.lowercased()
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// titleCaseString(s: "hello world") == "Hello World"
func titleCaseString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// capitalizeString(s: "hello world") == "Hello World"
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// capitalizeString(s: "hello world") == "Hello World"
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// capitalizeString(s: "hello world") == "Hello World"
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// capitalizeString(s: "hello world") == "Hello World"
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string with
// all the letters in title case.
// For example:
// capitalizeString(s: "hello world") == "Hello World"
func capitalizeString(s: String) -> String {
return String(s.capitalized)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string with
// all the
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as input and returns the string with
// all the vowels removed.
// For example:
// removeVowels(s: "Hello, world!") == "Hll, wrld!"
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 9
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return s.filter { !isVowel($0) } // cannot find 'isVowel' in scope
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func uppercaseString(s: String) -> String {
return s.uppercased()
}
func lowercaseString(s: String) -> String {
return s.lowercased()
}
func numberString(s: String) -> String {
return String(s.map { $0.unicodeScalarValue })
}
func numberStringExceptVowels(s: String) -> String {
return String(s.map {
switch $0.unicodeScalarValue {
case 97:
case 101:
case 105:
case 111:
case 117:
return ""
default:
return String($0.unicodeScalarValue)
}
})
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 1.1.2. Write a function that takes a string as input and returns the string
// with all the letters in reverse order.
// For example:
// reverseString(s: "Hello") == "olleH"
// reverseString(s: "Hello, world!") == "!dlrow ,olleH"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.1.3. Write a function that takes a string as input and returns the string
// with all the letters in uppercase.
// For example:
// uppercaseString(s: "Hello") == "HELLO"
// uppercaseString(s: "Hello, world!") == "HELLO, WORLD!"
func uppercaseString(s: String) -> String {
return s.uppercased()
}
// -----------------------------------------------------------------------------
// 1.1.4. Write a function that takes a string as input and returns the string
// with all the letters in lowercase.
// For example:
// lowercaseString(s: "Hello") == "hello"
// lowercaseString(s: "Hello, world!") == "hello, world!"
func lowercaseString(s: String) -> String {
return s.lowercased()
}
// -----------------------------------------------------------------------------
// 1.1.5. Write a function that takes a string as input and returns the string
// with all the letters replaced by their corresponding numbers.
// For example:
// numberString(s: "Hello") == "4433333333"
// numberString(s: "Hello, world!") == "4433333333, 44111111111!"
func numberString(s: String) -> String {
return String(s.map { $0.unicodeScalarValue })
}
// -----------------------------------------------------------------------------
// 1.1.6. Write a function that takes a string as input and returns the string
// with all the letters replaced by their corresponding numbers, except for the
// letters "a", "e", "i", "o", and "u".
// For example:
// numberStringExceptVowels(s: "Hello") == "4433333333"
// numberStringExceptVowels(s: "Hello, world!") == "4433333333, 44111111111!"
func numberStringExceptVowels(s: String) -> String {
return String(s.map {
switch $0.unicodeScalarValue {
case 97:
case 101:
case 105:
case 111:
case 117:
return ""
default:
return String($0.unicodeScalarValue)
}
})
}
// -----------------------------------------------------------------------------
// 1.1.7. Write a function that takes a string as input and returns the string
// with all the letters replaced by their corresponding numbers, except for the
// letters "a", "e", "i", "o", and "u", and the numbers "0", "1", "2", "3", and
// "4".
// For example:
// numberStringExceptVowelsAndNumbers(s: "Hello") == "4433333333"
// numberStringExceptVowelsAnd
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return String(s.map { $0.unicodeScalarValue }) // value of type 'String.Element' (aka 'Character') has no member 'unicodeScalarValue'
switch $0.unicodeScalarValue { // value of type 'String.Element' (aka 'Character') has no member 'unicodeScalarValue'
case 97: // 'case' label in a 'switch' must have at least one executable statement
case 101: // 'case' label in a 'switch' must have at least one executable statement
case 105: // 'case' label in a 'switch' must have at least one executable statement
case 111: // 'case' label in a 'switch' must have at least one executable statement
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// For example:
// removeVowels(s: "I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels(s: "aeiou") == ""
func removeVowels(s: String) -> String {
return s.filter { !"aeiou".contains($0) }
}
// ------------------
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
func vowels(s: String) -> Int {
return s.count(where: isVowel)
}
func noVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
func swapFirstLast(s: String) -> String {
return s.last + s[1..<s.count - 1] + s[0]
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
return s.split(separator: ", ").map { $0.trim() }
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as an argument and returns the
// number of vowels in the string. The vowels are "a", "e", "i", "o", and "u".
// You should treat the letter "y" as a consonant.
// For example:
// vowels(s: "Yo") == 2
// vowels(s: "Apple") == 3
// vowels(s: "Cucumber") == 5
func vowels(s: String) -> Int {
return s.count(where: isVowel)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as an argument and returns the
// string with all vowels removed.
// For example:
// noVowels(s: "Yo") == "Y"
// noVowels(s: "Apple") == "Ppl"
// noVowels(s: "Cucumber") == "Cmbr"
func noVowels(s: String) -> String {
return s.filter { !isVowel($0) }
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as an argument and returns a new
// string with the first and last characters swapped.
// For example:
// swapFirstLast(s: "Hello") == "oHell"
// swapFirstLast(s: "Goodbye") == "yobGd"
// swapFirstLast(s: "Z") == "Z"
func swapFirstLast(s: String) -> String {
return s.last + s[1..<s.count - 1] + s[0]
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as an argument and returns a new
// string with the first and last characters swapped.
// For example:
// swapFirstLast(s: "Hello") == "oHell"
// swapFirstLast(s: "Goodbye") == "yobGd"
// swapFirstLast(s: "Z") == "Z"
func swapFirstLast(s: String) -> String {
return s.last + s[1..<s.count - 1] + s[0]
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as an argument and returns a new
// string with the first and last characters swapped.
// For example:
// swapFirstLast(s: "Hello") == "oHell"
// swapFirstLast(s: "Goodbye") == "yobGd"
// swapFirstLast(s: "Z") == "Z"
func swapFirstLast(s: String) -> String {
return s.last + s[1..<s.count - 1] + s[0]
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as an argument and returns a new
// string with the first and last characters swapped.
// For example:
// swapFirstLast(s: "Hello") == "oHell"
// swapFirstLast(s: "Goodbye") == "yobGd"
// swapFirstLast(s: "Z") == "Z"
func swapFirstLast(s: String) -> String {
return s.last + s[1..<s.count - 1] + s[0]
}
// ---------------------------------------------------------------
return s.split(separator: ", ").map { $0.trim() } // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
return s.count(where: isVowel) // cannot call value of non-function type 'Int'
return s.count(where: isVowel) // cannot find 'isVowel' in scope
return s.filter { !isVowel($0) } // cannot find 'isVowel' in scope
return s.last + s[1..<s.count - 1] + s[0] // cannot convert value of type 'Character' to expected argument type 'String'
return s.last + s[1..<s.count - 1] + s[0] // cannot convert value of type 'String.Element?' (aka 'Optional<Character>') to expected argument type 'String'
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
return -1
}
func countVowels(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
var count = 0
var word = ""
for char in s {
if char == " " {
count += 1
word = ""
} else {
word += char
}
}
return count + 1
}
func countConsonants(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if !vowels.contains(char) {
count += 1
}
}
return count
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char.isUpper {
count += 1
}
}
return count
}
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char.isLower {
count += 1
}
}
return count
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
return -1
}
// -----------------------------------------------------------------------------
// Task 2.
// Write a function that takes a string and returns the number of vowels
// in the string. The vowels are 'a', 'e', 'i', 'o', and 'u'.
// For example:
// countVowels("apple") == 2
// countVowels("banana") == 3
func countVowels(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 3.
// Write a function that takes a string and returns the number of words
// in the string. A word is a sequence of non-whitespace characters.
// For example:
// countWords("Hello world") == 2
// countWords(" Hello world ") == 2
func countWords(s: String) -> Int {
var count = 0
var word = ""
for char in s {
if char == " " {
count += 1
word = ""
} else {
word += char
}
}
return count + 1
}
// -----------------------------------------------------------------------------
// Task 4.
// Write a function that takes a string and returns the number of
// consonants in the string. A consonant is a letter that is not
// 'a', 'e', 'i', 'o', or 'u'.
// For example:
// countConsonants("apple") == 3
// countConsonants("banana") == 5
func countConsonants(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if !vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 5.
// Write a function that takes a string and returns the number of
// uppercase letters in the string.
// For example:
// countUppercase("Hello world") == 1
// countUppercase(" Hello world ") == 2
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char.isUpper {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 6.
// Write a function that takes a string and returns the number of
// lowercase letters in the string.
// For example:
// countLowercase("Hello world") == 1
// countLowercase(" Hello world ") == 2
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char.isLower {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// Task 7.
// Write a function that takes a string and returns the number of
// digits in the string.
// For example:
// countDigits("Hello world") == 0
// countDigits(" Hello world ") == 0
// countDigits("12345") == 5
func countDigits(s: String
word += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isUpper { // value of type 'Character' has no member 'isUpper'
if char.isLower { // value of type 'Character' has no member 'isLower'
func chooseNum(x: Int, y: Int) -> Int {
var max = -1
for i in 1...y {
if i % 2 == 0 && i >= x {
max = i
}
}
return max
}
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var max = -1
for i in 1...y {
if i % 2 == 0 && i >= x {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var output = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
output += char
}
}
return output
}
// ------------
output += char // cannot convert value of type 'Character' to expected argument type 'String'
func chooseNum(x: Int, y: Int) -> Int {
var biggestEven = -1
for i in (x...y) {
if i % 2 == 0 && i > biggestEven {
biggestEven = i
}
}
return biggestEven
}
func stringLength(string: String) -> Int {
return string.count
}
func isPalindrome(string: String) -> Bool {
return string == string.reversed
}
func toLower(string: String) -> String {
return string.lowercased
}
func toUpper(string: String) -> String {
return string.uppercased
}
func removeSpaces(string: String) -> String {
return string.replacingOccurrences(with: " ")
}
func removeVowels(string: String) -> String {
return string.replacingOccurrences(with: "aeiouAEIOU")
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var biggestEven = -1
for i in (x...y) {
if i % 2 == 0 && i > biggestEven {
biggestEven = i
}
}
return biggestEven
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as a parameter and returns the
// length of the string.
// For example:
// stringLength("hello") == 5
func stringLength(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as a parameter and returns true
// if the string is a palindrome, and false otherwise. A palindrome is a
// string that's the same forwards and backwards.
// For example:
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(string: String) -> Bool {
return string == string.reversed
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all lowercase letters.
// For example:
// toLower("Hello") == "hello"
func toLower(string: String) -> String {
return string.lowercased
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all uppercase letters.
// For example:
// toUpper("Hello") == "HELLO"
func toUpper(string: String) -> String {
return string.uppercased
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all the spaces removed.
// For example:
// removeSpaces("Hello World") == "HelloWorld"
func removeSpaces(string: String) -> String {
return string.replacingOccurrences(with: " ")
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all the vowels removed.
// For example:
// removeVowels("Hello World") == "Hll Wrld"
func removeVowels(string: String) -> String {
return string.replacingOccurrences(with: "aeiouAEIOU")
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all the vowels removed.
// For example:
// removeVowels("Hello World") == "Hll Wrld"
func removeVowels(string: String) -> String {
return string.replacingOccurrences(with: "aeiouAEIOU")
}
// -----------------------------------------------------------------------------
// 9. Write a function that takes a string as a parameter and returns a new
// string that contains the same characters in the same order, but with
// all the vowels removed.
// For example:
// removeVowels("Hello World") == "Hll Wrld"
func removeVowels(string: String) -> String {
return string.replacingOcc
return string == string.reversed // type '() -> [String.Element]' (aka '() -> Array<Character>') cannot conform to 'StringProtocol'
return string.lowercased // function produces expected type 'String'; did you mean to call it with '()'?
return string.uppercased // function produces expected type 'String'; did you mean to call it with '()'?
return string.replacingOccurrences(with: " ") // missing argument for parameter 'of' in call
return string.replacingOccurrences(with: "aeiouAEIOU") // missing argument for parameter 'of' in call
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return y
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return y
}
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ---------------------------------------------------------------------
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in (x...y) {
if i % 2 == 0 {
result = i
}
}
return result
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var result = -1
for i in (x...y) {
if i % 2 == 0 {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return chooseNum(x + 1, y)
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return chooseNum(x + 1, y)
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
return chooseNum(x + 1, y) // missing argument labels 'x:y:' in call
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return y
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
} else {
return y
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
var biggestEven = -1
for i in (x...y) {
if i % 2 == 0 {
biggestEven = i
}
}
return biggestEven
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var biggestEven = -1
for i in (x...y) {
if i % 2 == 0 {
biggestEven = i
}
}
return biggestEven
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var maxEven = -1
for i in (x...y) {
if i % 2 == 0 {
maxEven = i
}
}
return maxEven
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var maxEven = -1
for i in (x...y) {
if i % 2 == 0 {
maxEven = i
}
}
return maxEven
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
// Fatal error: Range requires lowerBound <= upperBound
func chooseNum(x: Int, y: Int) -> Int {
var max = -1
for i in 0..<y {
if i % 2 == 0 && i >= x {
max = i
}
}
return max
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
var max = -1
for i in 0..<y {
if i % 2 == 0 && i >= x {
max = i
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
// XCTAssertTrue failed
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = (m - n + 1) * (n + m) / 2
let avg = sum / (m - n + 1)
return .success(String(UInt(avg), radix: 2))
}
func multiplesOfThreeOrFive(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 3 == 0 || number % 5 == 0 {
sum += number
}
}
if sum > 1000 {
return -1
}
return sum
}
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char) - 48
}
}
return sum
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = (m - n + 1) * (n + m) / 2
let avg = sum / (m - n + 1)
return .success(String(UInt(avg), radix: 2))
}
// Given an array of integers, return the sum of all of the integers that are
// multiples of 3 or 5. If the sum exceeds 1000, return -1 instead.
// Example:
// multiplesOfThreeOrFive([1, 2, 3, 4, 5, 6]) == 8
// multiplesOfThreeOrFive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 33
// multiplesOfThreeOrFive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 108
// multiplesOfThreeOrFive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == -1
func multiplesOfThreeOrFive(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 3 == 0 || number % 5 == 0 {
sum += number
}
}
if sum > 1000 {
return -1
}
return sum
}
// Given a string, return the sum of the digits that appear in the string, ignoring
// all other characters. If there are no digits in the string, return 0.
// Example:
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd22") == 8
// sumDigits("aa11bcd") == 0
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char) - 48
}
}
return sum
}
// Given a string, return the sum of the digits that appear in the string,
// ignoring all other characters. If there are no digits in the string, return 0.
// Example:
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd22") == 8
// sumDigits("aa11bcd") == 0
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char) - 48
}
}
return sum
}
// Given a string, return the sum of the digits that appear in the string,
// ignoring all other characters. If there are no digits in the string, return 0.
// Example:
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd22") == 8
// sumDigits("aa11bcd") == 0
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char) - 48
}
}
return sum
}
// Given a string, return the sum of the digits that appear in the string,
// ignoring all other characters. If there are no digits in the string, return 0.
// Example:
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd22") == 8
// sumDigits("aa11bcd") == 0
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += Int(char) - 48 // no exact matches in call to initializer
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example:
// sumOfPositives([1, 2, 3, 4, 5]) == 15
// sumOfPositives([-1, -2, -3, -4, -5]) == 0
// sumOfPositives([0]) == 0
// sumOfPositives([]) == 0
func sumOfPositives(numbers: [Int]) -> Int {
return numbers.filter { $0 > 0 }.reduce(0, \+ )
}
// Given an array of integers, return the sum of all the positive integers in the array.
// If there are no positive integers, return 0.
// Example
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // value of type 'Int' has no member 'map'
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // expected expression path in Swift key path
return numbers.filter { $0 > 0 }.reduce(0, \+ ) // missing argument for parameter #2 in call
return numbers.filter { $0 > 0 }.reduce(0, \+ ) // expected expression path in Swift key path
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).reduce(0, { (sum, i) -> Int in
sum + i
})
let avg = Int(sum / (m - n + 1))
return .success(String(format: "%0b", value: avg))
}
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.map { word -> String in
word.map { char -> Character in
if char.isUpper {
return char.toLower
} else {
return char.toUpper
}
}.join()
}.join()
return reversed.reversed().join()
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).reduce(0, { (sum, i) -> Int in
sum + i
})
let avg = Int(sum / (m - n + 1))
return .success(String(format: "%0b", value: avg))
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower
// case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " iNPUT eXAMPLE "
// "Example Input " ==> "iNPUT eXAMPLE "
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.map { word -> String in
word.map { char -> Character in
if char.isUpper {
return char.toLower
} else {
return char.toUpper
}
}.join()
}.join()
return reversed.reversed().join()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower
// case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " iNPUT eXAMPLE "
// "Example Input " ==> "iNPUT eXAMPLE "
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.map { word -> String in
word.map { char -> Character in
if char.isUpper {
return char.toLower
} else {
return char.toUpper
}
}.join()
}.join()
return reversed.reversed().join()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower
// case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " iNPUT eXAMPLE "
// "Example Input " ==> "iNPUT eXAMPLE "
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.map { word -> String in
word.map { char -> Character in
if char.isUpper {
return char.toLower
} else {
return char.toUpper
}
}.join()
}.join()
return reversed.reversed().join()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower
// case. Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " iNPUT eXAMPLE "
// "Example Input " ==> "iNPUT eXAMPLE "
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.map { word -> String in
word.map { char -> Character in
if char.isUpper {
return char.toLower
} else {
return char.to
let sum = Int(n)...Int(m).reduce(0, { (sum, i) -> Int in // value of type 'Int' has no member 'reduce'
return .success(String(format: "%0b", value: avg)) // extraneous argument label 'value:' in call
if char.isUpper { // value of type 'Substring.Element' (aka 'Character') has no member 'isUpper'
}.join() // value of type '[Character]' has no member 'join'
}.join() // value of type '[String]' has no member 'join'
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
func sumOfCharacters(s: String) -> Result<Int, Int> {
return .success(s.count)
}
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
// Given a string s, return the sum of all characters.
// Example:
// sumOfCharacters("abc") == .success(6)
// sumOfCharacters("abcdef") == .success(21)
// sumOfCharacters("") == .success(0)
func sumOfCharacters(s: String) -> Result<Int, Int> {
return .success(s.count)
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
// countA("") == .success(0)
func countA(s: String) -> Result<Int, Int> {
return .success(s.count("a"))
}
// Given a string s, return the number of times that the character "a" appears in s.
// Example:
// countA("abc") == .success(1)
// countA("abcaa") == .success(3)
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // value of type 'Int' has no member 'map'
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // expected expression path in Swift key path
return .success(s.count("a")) // cannot call value of non-function type 'Int'
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = sum / (m - n + 1)
return .success(String(UInt(avg), radix: 2))
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = sum / (m - n + 1)
return .success(String(UInt(avg), radix: 2))
}
// Given a string, return the string with all the consecutive duplicate
// characters removed.
// Example:
// removeConsecutiveDuplicates("aabbbccd") == "abcd"
// removeConsecutiveDuplicates("abbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // value of type 'Int' has no member 'map'
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // expected expression path in Swift key path
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
let binary = avg.toBinaryString()
return .success(binary)
}
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
let binary = avg.toBinaryString()
return .success(binary)
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "11111"
// digit5("") == ""
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "11111"
// digit5("") == ""
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "11111"
// digit5("") == ""
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "11111"
// digit5("") == ""
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "11111"
// digit5("") == ""
func digit5(digits: String) -> String {
return digits.map { $0 < "5" ? "0" : "1" }.joined()
}
// Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
// Return the result as a string.
// Example:
// digit5("234567") == "0010011"
// digit5("12345") == "00000"
// digit5("56789") == "
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // value of type 'Int' has no member 'map'
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // expected expression path in Swift key path
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.reversed()
let joined = String(reversed)
return joined.trim()
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+)
let avg = Int(sum / (m - n + 1))
return .success(String(UInt(avg), radix: 2))
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET a si HTI"
// " space here " ==> "SPACe HERE"
// "No spaces at all" ==> "nTalsE a ll"
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.reversed()
let joined = String(reversed)
return joined.trim()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET a si HTI"
// " space here " ==> "SPACe HERE"
// "No spaces at all" ==> "nTalsE a ll"
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.reversed()
let joined = String(reversed)
return joined.trim()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET a si HTI"
// " space here " ==> "SPACe HERE"
// "No spaces at all" ==> "nTalsE a ll"
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.reversed()
let joined = String(reversed)
return joined.trim()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET a si HTI"
// " space here " ==> "SPACe HERE"
// "No spaces at all" ==> "nTalsE a ll"
func transform(s: String) -> String {
let words = s.split(separator: " ")
let reversed = words.reversed()
let joined = String(reversed)
return joined.trim()
}
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "This is a test" ==> "tSET a si HTI"
// " space here " ==> "SPACe
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // value of type 'Int' has no member 'map'
let sum = Int(n)...Int(m).map { $0 + 1 }.reduce(0, \+) // expected expression path in Swift key path
let joined = String(reversed) // no exact matches in call to initializer
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
var sum = 0
for i in n...m {
sum += i
}
let avg = Int(Double(sum) / (m - n + 1))
let binary = String(format: "%0\(Int(log2(m - n + 1))" + "b" + "%", avg)
return .success(binary)
}
func longestSubstring(s: String) -> Int {
var maxLength = 0
var currentLength = 0
var previousChar = ""
for char in s {
if char == previousChar {
currentLength = 0
} else {
currentLength += 1
maxLength = max(maxLength, currentLength)
}
previousChar = char
}
return maxLength
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
var sum = 0
for i in n...m {
sum += i
}
let avg = Int(Double(sum) / (m - n + 1))
let binary = String(format: "%0\(Int(log2(m - n + 1))" + "b" + "%", avg)
return .success(binary)
}
// Given a string s, return the length of the longest substring between two
// equal characters, excluding the two characters. If there is no such substring,
// return 0.
// Example:
// longestSubstring("aa") == 0
// longestSubstring("abca") == 2
// longestSubstring("cbzxy") == 0
// longestSubstring("letelt") == 2
func longestSubstring(s: String) -> Int {
var maxLength = 0
var currentLength = 0
var previousChar = ""
for char in s {
if char == previousChar {
currentLength = 0
} else {
currentLength += 1
maxLength = max(maxLength, currentLength)
}
previousChar = char
}
return maxLength
}
// Given a string s, return the length of the longest substring between two
// equal characters, excluding the two characters. If there is no such substring,
// return 0.
// Example:
// longestSubstring("aa") == 0
// longestSubstring("abca") == 2
// longestSubstring("cbzxy") == 0
// longestSubstring("letelt") == 2
func longestSubstring(s: String) -> Int {
var maxLength = 0
var currentLength = 0
var previousChar = ""
for char in s {
if char == previousChar {
currentLength = 0
} else {
currentLength += 1
maxLength = max(maxLength, currentLength)
}
previousChar = char
}
return maxLength
}
// Given a string s, return the length of the longest substring between two
// equal characters, excluding the two characters. If there is no such substring,
// return 0.
// Example:
// longestSubstring("aa") == 0
// longestSubstring("abca") == 2
// longestSubstring("cbzxy") == 0
// longestSubstring("letelt") == 2
func longestSubstring(s: String) -> Int {
var maxLength = 0
var currentLength = 0
var previousChar = ""
for char in s {
if char == previousChar {
currentLength = 0
} else {
currentLength += 1
maxLength = max(maxLength, currentLength)
}
previousChar = char
}
return maxLength
}
// Given a string s, return the length of the longest substring between two
// equal characters, excluding the two characters. If there is no such substring,
// return 0.
// Example:
// longestSubstring("aa") == 0
// longestSubstring("abca") == 2
// longestSubstring("cbzxy") == 0
// longestSubstring("letelt") == 2
func longestSubstring(s: String) -> Int {
var maxLength = 0
var currentLength = 0
var previousChar = ""
for char in s {
if char == previousChar {
currentLength = 0
} else {
currentLength += 1
maxLength = max(maxLength, currentLength)
}
previousChar = char
}
return maxLength
}
// Given a string s, return the length of the longest substring between two
// equal characters, excluding the two characters. If there is no such substring,
// return 0.
// Example:
// longestSubstring("aa") == 0
// longestSubstring("abca") ==
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = 0
for i in n...m {
sum += i
}
let avg = Int(round(Double(sum) / (m - n + 1)))
return .success(String(UInt(avg), radix: 2))
}
func firstTwo(s: String) -> String {
if s.count <= 2 {
return s
}
return s.prefix(2)
}
func endsLy(s: String) -> Bool {
return s.hasSuffix("ly")
}
func twoChar(s: String, index: Int) -> String {
if index < 0 || index >= s.count {
return s.prefix(2)
}
return s[index..<index + 2]
}
func atFirst(s: String) -> String {
if s.count < 2 {
return s + "@"
}
return s[..<2]
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
let sum = 0
for i in n...m {
sum += i
}
let avg = Int(round(Double(sum) / (m - n + 1)))
return .success(String(UInt(avg), radix: 2))
}
// Given a string s, return the string made of its first two characters,
// so that if the string length is 2 or less, return it unchanged.
// If the string length is more than 2, return the first 2 letters.
// Example:
// firstTwo("Hello") == "He"
// firstTwo("abcdefg") == "ab"
// firstTwo("ab") == "ab"
func firstTwo(s: String) -> String {
if s.count <= 2 {
return s
}
return s.prefix(2)
}
// Given a string, return true if it ends in "ly".
// Example:
// endsLy("oddly") == true
// endsLy("y") == false
// endsLy("oddy") == false
func endsLy(s: String) -> Bool {
return s.hasSuffix("ly")
}
// Given a string and an index, return a string length 2 starting at the given index.
// If the index is too big or too small to define a string length 2, use the first 2
// chars. The string length will be at least 2.
// Example:
// twoChar("java", 0) == "ja"
// twoChar("java", 2) == "va"
// twoChar("java", 3) == "ja"
func twoChar(s: String, index: Int) -> String {
if index < 0 || index >= s.count {
return s.prefix(2)
}
return s[index..<index + 2]
}
// Given a string, return a string length 2 made of its first 2 chars.
// If the string length is less than 2, use '@' for the missing chars.
// Example:
// atFirst("hello") == "he"
// atFirst("hi") == "hi"
// atFirst("h") == "h@"
func atFirst(s: String) -> String {
if s.count < 2 {
return s + "@"
}
return s[..<2]
}
// Given a string, return a string length 2 made of its first 2 chars.
// If the string length is less than 2, use '@' for the missing chars.
// Example:
// atFirst("hello") == "he"
// atFirst("hi") == "hi"
// atFirst("h") == "h@"
func atFirst(s: String) -> String {
if s.count < 2 {
return s + "@"
}
return s[..<2]
}
// Given a string, return a string length 2 made of its first 2 chars.
// If the string length is less than 2, use '@' for the missing chars.
// Example:
// atFirst("hello") == "he"
// atFirst("hi") == "hi"
// atFirst("h") == "h@"
func atFirst(s: String) -> String {
if s.count < 2 {
return s + "@"
}
return s[..<2]
}
// Given a string, return a string length 2 made of its first 2 chars.
// If the string length is less than 2, use '@' for the missing chars.
// Example:
// atFirst("hello") == "he"
// atFirst("hi") == "hi"
// atFirst("h") == "h@"
func atFirst(s: String) -> String {
if s.count < 2 {
return s + "@"
}
return s[..<2]
}
extension Int: Error {
}
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
var sum = 0
for i in n...m {
sum += i
}
let avg = Int(round(Double(sum) / (m - n + 1)))
let binary = String(format: "%08b", number: avg)
return .success(binary)
}
func countPalindromicSubstrings(s: String) -> Int {
var count = 0
for i in 0..<s.count {
for j in 0..<3 {
let left = i - j
let right = i + j
if left < 0 || right >= s.count {
break
}
if s[left] == s[right] {
count += 1
} else {
break
}
}
}
return count
}
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in (i + 1)..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
```swift
extension Int: Error {
}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
if n > m {
return .failure(-1)
}
var sum = 0
for i in n...m {
sum += i
}
let avg = Int(round(Double(sum) / (m - n + 1)))
let binary = String(format: "%08b", number: avg)
return .success(binary)
}
// Given a string s, return the number of palindromic substrings in it.
// A string is a palindrome when it reads the same backward as forward.
// A substring is a contiguous sequence of characters within a string.
// Example:
// countPalindromicSubstrings("abc") == 3
// countPalindromicSubstrings("aaa") == 6
func countPalindromicSubstrings(s: String) -> Int {
var count = 0
for i in 0..<s.count {
for j in 0..<3 {
let left = i - j
let right = i + j
if left < 0 || right >= s.count {
break
}
if s[left] == s[right] {
count += 1
} else {
break
}
}
}
return count
}
// Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example:
// numIdenticalPairs([1,2,3,1,1,3]) == 4
// numIdenticalPairs([1,1,1,1]) == 6
// numIdenticalPairs([1,2,3]) == 0
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in (i + 1)..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example:
// numIdenticalPairs([1,2,3,1,1,3]) == 4
// numIdenticalPairs([1,1,1,1]) == 6
// numIdenticalPairs([1,2,3]) == 0
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in (i + 1)..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example:
// numIdenticalPairs([1,2,3,1,1,3]) == 4
// numIdenticalPairs([1,1,1,1]) == 6
// numIdenticalPairs([1,2,3]) == 0
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in (i + 1)..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example:
// numIdenticalPairs([1,2,3,1,1,3]) == 4
// num
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
if !hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
func doubleArray(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
result.append(i * 2)
}
return result
}
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 + $0 }
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
result.append(i * 2)
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 + $0 }
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 + $0 }
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 + $0 }
}
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 + $0 }
}
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4,
if !hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
func doubleArray(x: [Int]) -> [Int] { // invalid redeclaration of 'doubleArray(x:)'
func doubleArray(x: [Int]) -> [Int] { // invalid redeclaration of 'doubleArray(x:)'
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------
return x.filter { $0.hasNoEvenDigit } // value of type 'Int' has no member 'hasNoEvenDigit'
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
func sumOfEvenDigits(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) {
result += i
}
}
return result
}
func sumOfOddDigits(x: [Int]) -> Int {
var result = 0
for i in x {
if !hasEvenDigit(i) {
result += i
}
}
return result
}
func sumOfEvenDigitsGreaterThan5(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) && i > 5 {
result += i
}
}
return result
}
func sumOfEvenDigitsLessThan5(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) && i < 5 {
result += i
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given an array of positive integers x.
// Return the sum of all elements that has even digits.
// Note: Return 0 if no element has even digits.
// For example:
// sumOfEvenDigits(x: [12, 34, 55, 66]) == 126
// sumOfEvenDigits(x: [123, 456, 777, 888]) == 0
func sumOfEvenDigits(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) {
result += i
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Given an array of positive integers x.
// Return the sum of all elements that has odd digits.
// Note: Return 0 if no element has odd digits.
// For example:
// sumOfOddDigits(x: [12, 34, 55, 66]) == 155
// sumOfOddDigits(x: [123, 456, 777, 888]) == 0
func sumOfOddDigits(x: [Int]) -> Int {
var result = 0
for i in x {
if !hasEvenDigit(i) {
result += i
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Given an array of positive integers x.
// Return the sum of all elements that has even digits and is greater than 5.
// Note: Return 0 if no element has even digits.
// For example:
// sumOfEvenDigitsGreaterThan5(x: [12, 34, 55, 66]) == 126
// sumOfEvenDigitsGreaterThan5(x: [123, 456, 777, 888]) == 0
func sumOfEvenDigitsGreaterThan5(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) && i > 5 {
result += i
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Given an array of positive integers x.
// Return the sum of all elements that has even digits and is less than 5.
// Note: Return 0 if no element has even digits.
// For example:
// sumOfEvenDigitsLessThan5(x: [12, 34, 55, 66]) == 126
// sumOfEvenDigitsLessThan5(x: [123, 456, 777, 888]) == 0
func sumOfEvenDigitsLessThan5(x: [Int]) -> Int {
var result = 0
for i in x {
if hasEvenDigit(i) && i < 5 {
result += i
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Given an array of positive integers x.
// Return the sum of all elements that has odd digits and is greater than 5.
// Note: Return 0 if no element has odd digits.
// For example:
// sumOfOddDigitsGreaterThan5(x: [12, 34, 55, 66]) == 155
// sumOfOddDigitsGreaterThan5(x: [1
var result = [] // empty collection literal requires an explicit type
if !hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
if hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
if !hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
if hasEvenDigit(i) && i > 5 { // cannot find 'hasEvenDigit' in scope
if hasEvenDigit(i) && i < 5 { // cannot find 'hasEvenDigit' in scope
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
func hasEvenDigit(number: Int) -> Bool {
var digit = 0
while number > 0 {
digit = number % 10
if digit % 2 == 0 {
return true
}
number /= 10
}
return false
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
func hasEvenDigit(number: Int) -> Bool {
var digit = 0
while number > 0 {
digit = number % 10
if digit % 2 == 0 {
return true
}
number /= 10
}
return false
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
if !hasEvenDigit(i) { // missing argument label 'number:' in call
number /= 10 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
var result = [] // empty collection literal requires an explicit type
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) { // value of type 'Int' has no member 'digits'
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) { // value of type 'Int' has no member 'digits'
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) { // value of type 'Int' has no member 'digits'
if !(i.digits.contains(2) || i.digits.contains(4) || i.digits.contains(6) || i.digits.contains(8)) { // value of type 'Int' has no member 'digits'
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
return x.filter { $0.hasNoEvenDigit } // value of type 'Int' has no member 'hasNoEvenDigit'
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
func sumOfPositives(x: [Int]) -> Int {
return x.filter { $0 > 0 }.reduce(0, \1, \1)
}
func differenceBetweenLargestAndSmallest(x: [Int]) -> Int {
return x.max()! - x.min()!
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
return x.filter { $0.hasNoEvenDigit }
}
// 2. Given an array of integers, return the sum of all the positive integers in the array.
// Note: Return 0 if there are no positive integers in the array.
// For example:
// sumOfPositives(x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sumOfPositives(x: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]) == 0
func sumOfPositives(x: [Int]) -> Int {
return x.filter { $0 > 0 }.reduce(0, \1, \1)
}
// 3. Given an array of integers, return the difference between the largest and smallest integers in the array.
// Note: Return 0 if there is only one integer in the array.
// For example:
// differenceBetweenLargestAndSmallest(x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 9
// differenceBetweenLargestAndSmallest(x: [1, 2, 3, -4, 5, 6, 7, 8, 9, 10]) == 16
func differenceBetweenLargestAndSmallest(x: [Int]) -> Int {
return x.max()! - x.min()!
}
// 4. Given an array of integers, return true if the array contains a 3 next to a 3 somewhere.
// Note: Return false if the array doesn't have any 3s.
// For example:
// has33([1, 3, 3]) == true
// has33([1, 3, 1, 3]) == true
// has33([3, 1, 3]) == false
// has33([3, 1, 1, 3]) == false
// has33([3, 1, 3, 3]) == true
// has33([3, 3, 1, 3]) == true
// has33([3, 3, 3]) == true
// has33([1, 3, 1]) == false
// has33([1, 3, 3, 1, 3]) == true
// has33([1, 3, 1, 3, 1, 3]) == true
// has33([1, 3, 3, 1]) == false
// has33([1, 3, 1, 1, 3]) == true
// has33([1, 3, 1, 1, 3, 1, 3]) == true
// has33([1, 3, 3, 1, 1, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3]) == true
// has33([1, 3, 1, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3,
return x.filter { $0.hasNoEvenDigit } // value of type 'Int' has no member 'hasNoEvenDigit'
return x.filter { $0 > 0 }.reduce(0, \1, \1) // invalid component of Swift key path
return x.filter { $0 > 0 }.reduce(0, \1, \1) // invalid component of Swift key path
return x.filter { $0 > 0 }.reduce(0, \1, \1) // extra argument in call
return x.filter { $0 > 0 }.reduce(0, \1, \1) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if !hasEvenDigit(i) {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
if !hasEvenDigit(i) { // cannot find 'hasEvenDigit' in scope
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if Int(i.digits.filter { $0 % 2 == 0 }.count) == 0 {
result.append(i)
}
}
return result
}
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = []
for i in x {
if Int(i.digits.filter { $0 % 2 == 0 }.count) == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.12.1
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.2
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.3
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.4
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.5
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.6
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(x: [Int]) -> [Int] {
return x.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.12.7
// -----------------------------------------------------------------------------
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6
var result = [] // empty collection literal requires an explicit type
if Int(i.digits.filter { $0 % 2 == 0 }.count) == 0 { // value of type 'Int' has no member 'digits'
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}.sorted().map {
if $0 >= 1 && $0 <= 9 {
return "\($0)"
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}.sorted().map {
if $0 >= 1 && $0 <= 9 {
return "\($0)"
}
}
}
// 12. Write a function that takes a string as an argument and returns a string with the first
// and last characters swapped.
// For example:
// firstLast("Hello") == "oelH"
// firstLast("bad") == "bad"
// firstLast("") == ""
// firstLast("1") == "1"
// firstLast("1234") == "4231"
// firstLast("123456789") == "987654321"
// firstLast("1234567890") == "0987654321"
// firstLast("12345678901") == "10987654321"
// firstLast("123456789012") == "210987654321"
// firstLast("1234567890123") == "3210987654321"
// firstLast("12345678901234") == "43210987654321"
// firstLast("123456789012345") == "543210987654321"
// firstLast("1234567890123456")
// firstLast("12345678901234567")
// firstLast("123456789012345678")
// firstLast("1234567890123456789")
// firstLast("12345678901234567890")
// firstLast("123456789012345678901")
// firstLast("1234567890123456789012")
// firstLast("12345678901234567890123")
// firstLast("123456789012345678901234")
// firstLast("1234567890123456789012345")
// firstLast("12345678901234567890123456")
// firstLast("123456789012345678901234567")
// firstLast("1234567890123456789012345678")
// firstLast("12345678901234567890123456789")
// firstLast("123456789012345678901234567890")
// firstLast("1234567890123456789012345678901")
// firstLast("12345678901234567890123456789012")
// firstLast("123456789012345678901234567890123")
// firstLast("123
}.sorted().map { // cannot infer type of closure parameter '$0' without a type annotation
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
// 12. Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
// 13. Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
// 14. Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
// 15. Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six"
var result = [] // empty collection literal requires an explicit type
result.sort() // type 'Any' cannot conform to 'Comparable'
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}.sorted().map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}.sorted().map {
if $0 >= 1 && $0 <= 9 {
return "\(String($0))"
}
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
}.sorted().map { // cannot infer type of closure parameter '$0' without a type annotation
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.map { $0.capitalized }.sorted().reversed()
}
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.map { $0.capitalized }.sorted().reversed()
}
// 2.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// byDoubling(arr: [1, 2, 3]) == [2, 4, 6]
// byDoubling(arr: [4, 4, 4, 4]) == [8, 8, 8, 8]
// byDoubling(arr: [100, 200, 300]) == [200, 400, 600]
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 3.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// byDoubling(arr: [1, 2, 3]) == [2, 4, 6]
// byDoubling(arr: [4, 4, 4, 4]) == [8, 8, 8, 8]
// byDoubling(arr: [100, 200, 300]) == [200, 400, 600]
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 4.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// byDoubling(arr: [1, 2, 3]) == [2, 4, 6]
// byDoubling(arr: [4, 4, 4, 4]) == [8, 8, 8, 8]
// byDoubling(arr: [100, 200, 300]) == [200, 400, 600]
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 5.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// byDoubling(arr: [1, 2, 3]) == [2, 4, 6]
// byDoubling(arr: [4, 4, 4, 4]) == [8, 8, 8, 8]
// byDoubling(arr: [100, 200, 300]) == [200, 400, 600]
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 6.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// byDoubling(arr: [1, 2, 3]) == [2, 4, 6]
// byDoubling(arr: [4, 4, 4, 4]) == [8, 8, 8, 8]
// byDoubling(arr: [100, 200, 300]) == [200, 400, 600]
func byDoubling(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 7.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3]
var result = [] // empty collection literal requires an explicit type
return result.map { $0.capitalized }.sorted().reversed() // value of type 'Any' has no member 'capitalized'
func byLength(arr: [Int]) -> [String] {
let sorted = arr.sorted()
let result = []
for i in sorted {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.reversed()
}
func byVowel(str: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in str {
if !vowels.contains(char) {
result += char
}
}
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let sorted = arr.sorted()
let result = []
for i in sorted {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.reversed()
}
// 2. Write a function that takes a string and returns a new string with all vowels removed.
// For example, "This website is for losers LOL!" should become "Ths wbst s fr lsrs LL!".
// Note: for this kata y isn't considered a vowel.
// byVowel("This website is for losers LOL!") == "Ths wbst s fr lsrs LL!"
// byVowel("No offense but, your writing is among the worst I've ever read") == "N ffns bt, ytt r'r wrttng s mng thwr rd"
// byVowel("What are you, a communist?") == "Wht r y, cmmnst?"
func byVowel(str: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in str {
if !vowels.contains(char) {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a new string with all the vowels removed.
// for example:
// byVowel("This website is for losers LOL!") == "Ths wbst s fr lsrs LL!"
// byVowel("No offense but, your writing is among the worst I've ever read") == "N ffns bt, ytt r'r wrttng s mng thwr rd"
// byVowel("What are you, a communist?") == "Wht r y, cmmnst?"
// byVowel("") == ""
// byVowel("a") == ""
// byVowel("b") == "b"
// byVowel("c") == "c"
// byVowel("d") == "d"
// byVowel("e") == ""
// byVowel("f") == "f"
// byVowel("g") == "g"
// byVowel("h") == "h"
// byVowel("i") == ""
// byVowel("j") == "j"
// byVowel("k") == "k"
// byVowel("l") == "l"
// byVowel("m") == "m"
// byVowel("n") == "n"
// byVowel("o") == ""
// byVowel("p") == "p"
// byVowel("q") == "q"
// byVowel("r") == "r"
// byVowel("s") == "s"
// byVowel("t") == "t"
// byVowel("u") == ""
// byVowel("v") == "v"
// byVowel("w") == "w"
// byVowel("x") == "x"
// byVowel("y") == ""
// byVowel("z") == "z"
// byVowel("") == ""
// byVowel("a") == ""
// byVowel("b") == "b"
// byVowel("c") == "c"
// byVowel("d") == "d"
// byVowel("e") == ""
// byVowel("f") == "f"
// byVowel("g") == "g"
// byVowel("h") == "h"
// byVowel("i") == ""
// byVowel("j") == "j"
// byVowel("k
let result = [] // empty collection literal requires an explicit type
result.append(String(i)) // cannot use mutating member on immutable value: 'result' is a 'let' constant
return result.reversed() // no 'reversed' candidates produce the expected contextual result type '[String]'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func byLength(arr: [Int]) -> [String] {
return arr.map {
if 1 <= $0 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted().map {
switch $0 {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
case 4:
return "Four"
case 5:
return "Five"
case 6:
return "Six"
case 7:
return "Seven"
case 8:
return "Eight"
case 9:
return "Nine"
default:
return ""
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if 1 <= $0 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted().map {
switch $0 {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
case 4:
return "Four"
case 5:
return "Five"
case 6:
return "Six"
case 7:
return "Seven"
case 8:
return "Eight"
case 9:
return "Nine"
default:
return ""
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
}.sorted().map { // cannot infer type of closure parameter '$0' without a type annotation
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 > 0 && $0 < 10 {
return "One"
} else if $0 > 9 && $0 < 100 {
return "Two"
} else if $0 > 99 && $0 < 1000 {
return "Three"
} else if $0 > 999 && $0 < 10000 {
return "Four"
} else if $0 > 9999 && $0 < 100000 {
return "Five"
} else if $0 > 99999 && $0 < 1000000 {
return "Six"
} else if $0 > 999999 && $0 < 10000000 {
return "Seven"
} else if $0 > 9999999 && $0 < 100000000 {
return "Eight"
} else if $0 > 99999999 && $0 < 1000000000 {
return "Nine"
} else {
return ""
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 > 0 && $0 < 10 {
return "One"
} else if $0 > 9 && $0 < 100 {
return "Two"
} else if $0 > 99 && $0 < 1000 {
return "Three"
} else if $0 > 999 && $0 < 10000 {
return "Four"
} else if $0 > 9999 && $0 < 100000 {
return "Five"
} else if $0 > 99999 && $0 < 1000000 {
return "Six"
} else if $0 > 999999 && $0 < 10000000 {
return "Seven"
} else if $0 > 9999999 && $0 < 100000000 {
return "Eight"
} else if $0 > 99999999 && $0 < 1000000000 {
return "Nine"
} else {
return ""
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = []
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
result.sort()
result.reverse()
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------
var result = [] // empty collection literal requires an explicit type
result.sort() // type 'Any' cannot conform to 'Comparable'
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted().map {
return String($0)
}.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted().map {
return String($0)
}.reversed()
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Write a function that takes a string as an argument and returns a new string that contains the same
// characters that are present in the original string, but sorted in alphabetical order.
// For example:
// byAlphabeticalOrder("hello") == "ehllo"
// byAlphabeticalOrder("goodbye") == "bbdgooy"
// byAlphabeticalOrder("") == ""
// byAlphabeticalOrder("h") == "h"
// byAlphabeticalOrder("a") == "a"
// byAlphabeticalOrder("z") == "z"
// byAlphabeticalOrder("zz") == "zz"
// byAlphabeticalOrder("zzzz") == "zzzz"
// byAlphabeticalOrder("ab") == "abb"
// byAlphabeticalOrder("aabb") == "aabb"
// byAlphabeticalOrder("aabbcc") == "aabbcc"
// byAlphabeticalOrder("abcdefghijklmnopqrstuvwxyz") == "abcdefghijklmnopqrstuvwxyz"
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba") == "abcdefghijklmnopqrstuvwxyz"
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjihgfedcba")
// byAlphabeticalOrder("zyxwvutsrqponmlkjih
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted(by: <).map {
switch $0 {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
case 4:
return "Four"
case 5:
return "Five"
case 6:
return "Six"
case 7:
return "Seven"
case 8:
return "Eight"
case 9:
return "Nine"
default:
return ""
}
}
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
return arr.map {
if $0 >= 1 && $0 <= 9 {
return String($0)
} else {
return ""
}
}.sorted(by: <).map {
switch $0 {
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
case 4:
return "Four"
case 5:
return "Five"
case 6:
return "Six"
case 7:
return "Seven"
case 8:
return "Eight"
case 9:
return "Nine"
default:
return ""
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
return String($0) // cannot convert value of type 'String' to closure result type 'UInt8'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
import Foundation
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(5))<|endoftext|>//
// main.swift
// 1.1.1
//
// Created by 임성민 on 2021/04/12.
//
import Foundation
var input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
var result = 0
for i in 1...100 {
if i % 3 == 0 {
result += i
}
}
print(result)<|endoftext|>//
// main.swift
// 1.1.1
//
// Created by 임성민 on 2021/04/12.
//
import Foundation
var input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 7
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(5))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
import Foundation
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(5))<|endoftext|>//
// main.swift
// Task 1
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
sum += i
}
print(sum)<|endoftext|>//
// main.swift
// Task 2
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// Task 3
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 != 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// Task 4
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// Task 5
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// Task 6
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// Task 7
//
// Created by Даниил on 15.03.2021.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9,
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(n: 5))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
import Foundation
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(5))<|endoftext|>//
// main.swift
// 10.1
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
sum += i
}
print(sum)<|endoftext|>//
// main.swift
// 10.2
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 10.3
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// 10.4
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// 10.5
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// 10.6
//
// Created by 임현성 on 2021/03/02.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
if i % 2 == 0 {
sum += i
} else {
sum -= i
}
}
print(sum)<|endoftext|>//
// main.swift
// 10.7
//
//
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(start: Int, end: Int) -> Int {
var result = 0
for i in start...end {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(start: Int, end: Int) -> Int {
var result = 0
for i in start...end {
result += i
}
return result
}
print(f(n: 5))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'start:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
result.append(sum(1...i)) // missing argument for parameter 'end' in call
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
import Foundation
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func factorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(to: Int) -> Int {
var result = 0
for i in 1...to {
result += i
}
return result
}
print(f(n: 5))<|endoftext|>//
// main.swift
// Task 1
//
// Created by Denys Yatsenko on 10.04.2020.
// Copyright © 2020 Denys Yatsenko. All rights reserved.
//
import Foundation
// Task 1
// Write a function that takes an integer and returns the number of 1 bits it has.
// Example:
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 10101010101010101010101010101010
// 101010
result.append(factorial(i)) // missing argument label 'n:' in call
result.append(sum(1...i)) // missing argument label 'to:' in call
result.append(sum(1...i)) // cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Int'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5
result.append(factorial(i)) // cannot find 'factorial' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(sum(1...i))
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// 2. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 3, 6, 10, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(sum(1...i))
}
return result
}
// 3. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
// 4. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
// 5. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
// 6. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
// 7. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i)
}
return result
}
// 8. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 2, 3, 4, 5]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(factorial(i)) // cannot find 'factorial' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(sum(1...i))
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 3 == 0 {
result.append(sum(1...i))
}
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 5 == 0 {
result.append(sum(1...i))
}
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 7 == 0 {
result.append(sum(1...i))
}
}
return result
}
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 11 == 0 {
result.append(sum(1...i))
}
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(1...i))
}
}
return result
}
// 2. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i.
// i starts from 1.
// Example:
// f(n: 5) == [1, 3, 6, 10, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(sum(1...i))
}
return result
}
// 3. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i,
// and the sum is divisible by 3.
// i starts from 1.
// Example:
// f(n: 5) == [1, 3, 6, 10, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 3 == 0 {
result.append(sum(1...i))
}
}
return result
}
// 4. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i,
// and the sum is divisible by 5.
// i starts from 1.
// Example:
// f(n: 5) == [1, 5, 10, 15, 20]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 5 == 0 {
result.append(sum(1...i))
}
}
return result
}
// 5. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i,
// and the sum is divisible by 7.
// i starts from 1.
// Example:
// f(n: 5) == [1, 7, 14, 21, 28]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 7 == 0 {
result.append(sum(1...i))
}
}
return result
}
// 6. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i,
// and the sum is divisible by 11.
// i starts from 1.
// Example:
// f(n: 5) == [1, 11, 22, 33, 44]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if sum(1...i) % 11 == 0 {
result.append(sum(1...i))
}
}
return result
}
// 7. Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the sum of numbers from 1 to i,
// and the sum is divisible by 13.
// i starts from 1.
// Example:
// f(n: 5) == [1,
result.append(factorial(i)) // cannot find 'factorial' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
if sum(1...i) % 3 == 0 { // cannot find 'sum' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
if sum(1...i) % 5 == 0 { // cannot find 'sum' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
if sum(1...i) % 7 == 0 { // cannot find 'sum' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func f(n: Int) -> [Int] { // invalid redeclaration of 'f(n:)'
if sum(1...i) % 11 == 0 { // cannot find 'sum' in scope
result.append(sum(1...i)) // cannot find 'sum' in scope
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = i
var t = i
while s > 0 {
t = t * 10 + s % 10
s /= 10
}
if t == i {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
func consecutiveOnes(n: Int) -> Int {
var count = 0
var prev = 0
var curr = 0
for i in 1...n {
prev = curr
curr = (prev + 1) % 2
if prev == 1 && curr == 1 {
count += 1
}
}
return n - count
}
func trailingZeroes(n: Int) -> Int {
var count = 0
while n > 0 {
count += n / 5
n /= 5
}
return count
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = i
var t = i
while s > 0 {
t = t * 10 + s % 10
s /= 10
}
if t == i {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
// 10.11
// Given a positive integer n, return the number of positive integers less than or equal to n, whose binary representations do not contain consecutive ones.
// Example 1:
// Input: 5
// Output: 5
// Explanation:
// Here are the non-negative integers <= 5 with their corresponding binary representations:
// 0 : 0
// 1 : 1
// 2 : 10
// 3 : 11
// 4 : 100
// 5 : 101
// Among them, only integer 3 disobeys the rule (two consecutive ones in its binary representation) and the other 5 satisfy the rule.
// Example 2:
// Input: 1
// Output: 2
// Explanation:
// Since there is only one integer that fits the given rules, 1 does satisfy the rule.
// Note that 2 does not satisfy the rule because there are consecutive ones in its binary representation: 10.
// Note:
// 1. 1 <= n <= 10^9
// 2. The answer is guaranteed to fit in a 32-bit signed integer.
// consecutiveOnes(n: 5) == 5
// consecutiveOnes(n: 1) == 2
func consecutiveOnes(n: Int) -> Int {
var count = 0
var prev = 0
var curr = 0
for i in 1...n {
prev = curr
curr = (prev + 1) % 2
if prev == 1 && curr == 1 {
count += 1
}
}
return n - count
}
// 10.12
// Given an integer n, return the number of trailing zeroes in n!.
// Example 1:
// Input: 3
// Output: 0
// Explanation: 3! = 6, no trailing zero.
// Example 2:
// Input: 5
// Output: 1
// Explanation: 5! = 120, one trailing zero.
// Note: Your solution should be in logarithmic time complexity.
// Note:
// 1. 1 <= n <= 10^4
// 2. The answer is guaranteed to fit in a 32-bit signed integer.
// trailingZeroes(n: 3) == 0
// trailingZeroes(n: 5) == 1
func trailingZeroes(n: Int) -> Int {
var count = 0
while n > 0 {
count += n / 5
n /= 5
}
return count
}
// 10.13
// Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
// Example 1:
// Input: n = 12
// Output: 3
// Explanation: 12 = 4 + 4 + 4.
// Example 2:
// Input: n = 13
// Output: 2
// Explanation: 13 = 4 + 9.
// Note:
// 1. 1 <= n <= 10^4
// 2. The answer is guaranteed to fit in a 32-bit signed integer.
// numSquares(n: 12) == 3
// numSquares(n: 13) == 2
func numSquares(n: Int) -> Int {
var dp = [Int.max] * (n + 1)
dp[0] = 0
for i in 1...n {
for j in 1...Int(sqrt(Double(i))) {
dp[i] = min(dp[i],
for i in 1...n { // immutable value 'i' was never used; consider replacing with '_' or removing it
n /= 5 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 2. Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 3. Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 4. Given a positive integer n, return the number of palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd =
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 2. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 3. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 4. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) ==
var s = String(i) // variable 's' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s[..<s.count]).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s[..<s.count]).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
print(evenOddPalindrome(3))
print(evenOddPalindrome(12))
// 10. Write a function that takes a string as input and returns the string reversed.
// Example 1:
// Input: "hello"
// Output: "olleh"
// Example 2:
// Input: "A man, a plan, a canal: Panama"
// Output: "amanaP :lanac a ,nalp a ,nam A"
// Note:
// 1. What constitutes a palindrome?
// 2. Did you ignore case?
// 3. There are four important cases to consider:
// 1. Empty string
// 2. Single character
// 3. Palindrome with even number of characters
// 4. Palindrome with odd number of characters
// 4. What are the base cases?
// 5. How do you handle the case where the input string is empty?
// 6. How do you handle the case where the input string has only one character?
// 7. How do you handle the case where the input string has only two characters?
// 8. How do you handle the case where the input string has more than two characters?
// 9. How do you handle the case where the input string has even number of characters?
// 10. How do you handle the case where the input string has odd number of characters?
// 11. How do you handle the case where the input string has spaces?
// 12. How do you handle the case where the input string has non-alphanumeric characters?
// 13. How do you handle the case where the input string has uppercase and lowercase letters?
// 14. How do you handle the case where the input string has uppercase and lowercase letters and spaces?
// 15. How do you handle the case where the input string has uppercase and lowercase letters, spaces, and non-alphanumeric characters?
// 16. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, and spaces?
// 17. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, and spaces?
// 18. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, and spaces?
// 19. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, and spaces?
// 20. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, and spaces?
// 21. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, spaces, and spaces?
// 22. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, spaces, spaces, and spaces?
// 23. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, spaces, spaces, spaces, and spaces?
// 24. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, spaces, spaces, spaces, spaces, and spaces?
// 25. How do you handle the case where the input string has uppercase and lowercase letters, spaces, non-alphanumeric characters, spaces, spaces, spaces, spaces, spaces, spaces, spaces, spaces, spaces, and spaces?
// 26. How do you handle the case where the input
var s = String(i) // variable 's' was never mutated; consider changing to 'let' constant
if s == String(String(s[..<s.count]).reversed()) { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
var isPalindrome = true
for j in 0..<s.count/2 {
if s[j] != s[s.count-1-j] {
isPalindrome = false
break
}
}
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func romanToInt(s: String) -> Int {
var result = 0
var i = 0
while i < s.count {
switch s[i] {
case 'I':
if i+1 < s.count && s[i+1] == 'V' {
result += 4
i += 2
} else if i+1 < s.count && s[i+1] == 'X' {
result += 9
i += 2
} else {
result += 1
i += 1
}
case 'V':
result += 5
i += 1
case 'X':
if i+1 < s.count && s[i+1] == 'L' {
result += 40
i += 2
} else if i+1 < s.count && s[i+1] == 'C' {
result += 90
i += 2
} else {
result += 10
i += 1
}
case 'L':
result += 50
i += 1
case 'C':
if i+1 < s.count && s[i+1] == 'D' {
result += 400
i += 2
} else if i+1 < s.count && s[i+1] == 'M' {
result += 900
i += 2
} else {
result += 100
i += 1
}
case 'D':
result += 500
i += 1
case 'M':
result += 1000
i += 1
default:
break
}
}
return result
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
var isPalindrome = true
for j in 0..<s.count/2 {
if s[j] != s[s.count-1-j] {
isPalindrome = false
break
}
}
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
print(evenOddPalindrome(12))
print(evenOddPalindrome(3))
// -----------------------------------------------------------------------------
// 13. 13. Roman to Integer
// Given a roman numeral, convert it to an integer.
// Input is guaranteed to be within the range from 1 to 3999.
// Example 1:
// Input: "III"
// Output: 3
// Example 2:
// Input: "IV"
// Output: 4
// Example 3:
// Input: "IX"
// Output: 9
// Example 4:
// Input: "LVIII"
// Output: 58
// Explanation: L = 50, V= 5, III = 3.
// Example 5:
// Input: "MCMXCIV"
// Output: 1994
// Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
func romanToInt(s: String) -> Int {
var result = 0
var i = 0
while i < s.count {
switch s[i] {
case 'I':
if i+1 < s.count && s[i+1] == 'V' {
result += 4
i += 2
} else if i+1 < s.count && s[i+1] == 'X' {
result += 9
i += 2
} else {
result += 1
i += 1
}
case 'V':
result += 5
i += 1
case 'X':
if i+1 < s.count && s[i+1] == 'L' {
result += 40
i += 2
} else if i+1 < s.count && s[i+1] == 'C' {
result += 90
i += 2
} else {
result += 10
i += 1
}
case 'L':
result += 50
i += 1
case 'C':
if i+1 < s.count && s[i+1] == 'D' {
result += 400
i += 2
} else if i+1 < s.count && s[i+1] == 'M' {
result += 900
i += 2
} else {
result += 100
i += 1
}
case 'D':
result += 500
i += 1
case 'M':
result += 1000
i += 1
default:
break
}
}
return result
}
print(romanToInt("III"))
print(romanToInt("IV"))
print(romanToInt("IX"))
print(romanToInt("LVIII"))
print(romanToInt("MCMXCIV"))
// -----------------------------------------------------------------------------
// 14. 14. Longest Common Prefix
// Write a function to find the longest common prefix string amongst an array of strings.
// If there is no common prefix, return an empty string "".
// Example 1:
// Input: ["flower","flow","flight"]
// Output: "
var s = String(i) // variable 's' was never mutated; consider changing to 'let' constant
if s[j] != s[s.count-1-j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[j] != s[s.count-1-j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
switch s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
case 'I': // single-quoted string literal found, use '"'
if i+1 < s.count && s[i+1] == 'V' { // single-quoted string literal found, use '"'
if i+1 < s.count && s[i+1] == 'V' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if i+1 < s.count && s[i+1] == 'X' { // single-quoted string literal found, use '"'
} else if i+1 < s.count && s[i+1] == 'X' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
case 'V': // single-quoted string literal found, use '"'
case 'X': // single-quoted string literal found, use '"'
if i+1 < s.count && s[i+1] == 'L' { // single-quoted string literal found, use '"'
if i+1 < s.count && s[i+1] == 'L' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if i+1 < s.count && s[i+1] == 'C' { // single-quoted string literal found, use '"'
} else if i+1 < s.count && s[i+1] == 'C' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
case 'L': // single-quoted string literal found, use '"'
case 'C': // single-quoted string literal found, use '"'
if i+1 < s.count && s[i+1] == 'D' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i+1 < s.count && s[i+1] == 'D' { // single-quoted string literal found, use '"'
} else if i+1 < s.count && s[i+1] == 'M' { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
} else if i+1 < s.count && s[i+1] == 'M' { // single-quoted string literal found, use '"'
case 'D': // single-quoted string literal found, use '"'
case 'M': // single-quoted string literal found, use '"'
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 2. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 3. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s.reversed()).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 4. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) ==
var s = String(i) // variable 's' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 2. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 3. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
var s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 4. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func even
var s = String(i) // variable 's' was never mutated; consider changing to 'let' constant
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let s = String(i)
if s == String(String(s).reversed()) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
print(evenOddPalindrome(12))
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
var isPalindrome = true
var reversed = 0
var number = i
while number > 0 {
reversed = reversed * 10 + number % 10
number /= 10
}
if reversed == i {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
var isPalindrome = true
var reversed = 0
var number = i
while number > 0 {
reversed = reversed * 10 + number % 10
number /= 10
}
if reversed == i {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
var result = evenOddPalindrome(12)
print("result: \(result)")
// 2. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
var isPalindrome = true
var reversed = 0
var number = i
while number > 0 {
reversed = reversed * 10 + number % 10
number /= 10
}
if reversed == i {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
var result = evenOddPalindrome(12)
print("result: \(result)")
// 3. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var evenCount = 0
var oddCount = 0
for i in 1...n {
var isPalindrome = true
var reversed = 0
var number = i
while number > 0 {
reversed = reversed * 10 + number % 10
number /= 10
}
if reversed == i {
if i % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
}
return (evenCount, oddCount)
}
var result = evenOddPalindrome(12)
print("result: \(result)")
// 4. Given a positive integer n, return a tuple that has the number
var isPalindrome = true // initialization of variable 'isPalindrome' was never used; consider replacing with assignment to '_' or removing it
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if String(i) == String(i).reversed() {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
if String(i) == String(i).reversed() {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
// 2. 2. Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(n, 2n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196
if String(i) == String(i).reversed() { // cannot convert value of type 'ReversedCollection<String>' to expected argument type 'String'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 2. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 3. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 4. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 5. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 6. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// 7. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
//
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
let sum = num.digits().reduce(0, \1 + \2)
if sum > 0 {
count += 1
}
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
let sum = num.digits().reduce(0, \1 + \2)
if sum > 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
let sum = num.digits().reduce(0, \1 + \2) // invalid component of Swift key path
let sum = num.digits().reduce(0, \1 + \2) // value of type 'Int' has no member 'digits'
let sum = num.digits().reduce(0, \1 + \2) // invalid component of Swift key path
let sum = num.digits().reduce(0, \1 + \2) // binary operator '+' cannot be applied to two 'WritableKeyPath<_, _>' operands
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
func vowels(s: String) -> Int {
return s.count(where: \Character.isVowel)
}
func words(s: String) -> Int {
return s.split(.whitespace).count
}
func consonants(s: String) -> Int {
return s.count(where: \Character.isConsonant)
}
func uppercase(s: String) -> Int {
return s.count(where: \Character.isUpper)
}
func lowercase(s: String) -> Int {
return s.count(where: \Character.isLower)
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of vowels
// in the string.
// Note: the vowel letters are a, e, i, o, u.
// vowels("Hello") == 2
// vowels("Why do you ask?") == 4
// vowels("Why?") == 0
// vowels("C is cool!") == 2
func vowels(s: String) -> Int {
return s.count(where: \Character.isVowel)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of words
// in the string.
// Note: a word is defined as a sequence of non-space characters.
// words("Hello") == 1
// words("Hello, World!") == 2
// words("One") == 1
// words("") == 0
// words("Hi, my name is John") == 5
func words(s: String) -> Int {
return s.split(.whitespace).count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of
// consonants in the string.
// Note: a consonant is a letter which is not a, e, i, o, u.
// consonants("Hello") == 3
// consonants("Why do you ask?") == 5
// consonants("Why?") == 0
// consonants("C is cool!") == 7
func consonants(s: String) -> Int {
return s.count(where: \Character.isConsonant)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of
// uppercase letters in the string.
// Note: a letter is a 26-letter alphabet.
// uppercase("Hello") == 1
// uppercase("Why do you ask?") == 1
// uppercase("Why?") == 0
// uppercase("C is cool!") == 1
func uppercase(s: String) -> Int {
return s.count(where: \Character.isUpper)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of
// lowercase letters in the string.
// Note: a letter is a 26-letter alphabet.
// lowercase("Hello") == 1
// lowercase("Why do you ask?") == 3
// lowercase("Why?") == 0
// lowercase("C is cool!") == 1
func lowercase(s: String) -> Int {
return s.count(where: \Character.isLower)
}
// ---------------------
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
return s.count(where: \Character.isVowel) // value of type 'Character' has no member 'isVowel'
return s.count(where: \Character.isVowel) // cannot call value of non-function type 'Int'
return s.split(.whitespace).count // no exact matches in call to instance method 'split'
return s.split(.whitespace).count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return s.count(where: \Character.isConsonant) // cannot call value of non-function type 'Int'
return s.count(where: \Character.isConsonant) // value of type 'Character' has no member 'isConsonant'
return s.count(where: \Character.isUpper) // cannot call value of non-function type 'Int'
return s.count(where: \Character.isUpper) // value of type 'Character' has no member 'isUpper'
return s.count(where: \Character.isLower) // value of type 'Character' has no member 'isLower'
return s.count(where: \Character.isLower) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.1
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.2
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.3
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.4
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.5
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 >
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n = n / 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n = n / 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 10. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n = n / 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n = n / 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
if num > 0 {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n = n / 10
}
if sum > 0 {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr:
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 12. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 13. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 14. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 15. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 16. Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// ---------------------------------------------------
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.1
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.2
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.3
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.4
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// 1.10.5
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 >
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
return arr.count(where: { $0 > 0 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
return arr.count(where: { $0 > 0 }) // cannot call value of non-function type 'Int'
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
i += 1
}
return count <= 1
}
func lengthOfLongestSubstring(s: String) -> Int {
var maxLength = 0
var start = 0
var end = 0
var charSet = Set<Character>()
while end < s.count {
if charSet.contains(s[end]) {
charSet.remove(s[start])
start += 1
} else {
charSet.insert(s[end])
end += 1
maxLength = max(maxLength, end - start)
}
}
return maxLength
}
func lengthOfLIS(nums: [Int]) -> Int {
var dp = [1] * nums.count
var maxLength = 1
for i in nums.reversed() {
for j in nums.indices() {
if i < nums[j] {
dp[j] = max(dp[j], dp[i] + 1)
maxLength = max(maxLength, dp[j])
}
}
}
return maxLength
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
i += 1
}
return count <= 1
}
// 2.
// Given a string s, find the length of the longest substring without repeating
// characters.
// Example 1:
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: s = "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: s = "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Notice that the answer must be a substring, "pwke" is a subsequence and not a
// substring.
// Example 4:
// Input: s = ""
// Output: 0
// Constraints:
// 0 <= s.length <= 5 * 104
// s consists of English letters, digits, symbols and spaces.
func lengthOfLongestSubstring(s: String) -> Int {
var maxLength = 0
var start = 0
var end = 0
var charSet = Set<Character>()
while end < s.count {
if charSet.contains(s[end]) {
charSet.remove(s[start])
start += 1
} else {
charSet.insert(s[end])
end += 1
maxLength = max(maxLength, end - start)
}
}
return maxLength
}
// 3.
// Given an integer array nums, return the length of the longest strictly
// increasing subsequence.
// A subsequence is a sequence that can be derived from an array by deleting
// some or no elements without changing the order of the remaining elements.
// For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
// Example 1:
// Input: nums = [10,9,2,5,3,7,101,18]
// Output: 4
// Explanation: The longest increasing subsequence is [2,3,7,101], therefore the
// length is 4.
// Example 2:
// Input: nums = [0,1,0,3,2,3]
// Output: 4
// Example 3:
// Input: nums = [7,7,7,7,7,7,7]
// Output: 1
// Constraints:
// 1 <= nums.length <= 2500
// -104 <= nums[i] <= 104
// Follow up:
// Could you come up with the O(n2) solution?
// Could you come up with the O(n log(n)) solution using only constant space
// complexity?
func lengthOfLIS(nums: [Int]) -> Int {
var dp = [1] * nums.count
var maxLength = 1
for i in nums.reversed() {
for j in nums.indices() {
if i < nums[j] {
dp[j] = max(dp[j], dp[i] + 1)
maxLength = max(maxLength, dp[j])
}
}
}
return maxLength
}
// 4.
// Given an integer array nums, return the length of the longest strictly
// increasing subsequence.
// A subsequence is a sequence that can be derived from an array by deleting
// some or no elements without changing the order of the remaining elements.
// For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
// Example 1:
// Input: nums = [10,9,2,5,3,7,101,18]
// Output: 4
// Explanation: The longest increasing
if charSet.contains(s[end]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
charSet.remove(s[start]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
charSet.insert(s[end]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
var dp = [1] * nums.count // binary operator '*' cannot be applied to operands of type '[Int]' and 'Int'
for j in nums.indices() { // cannot call value of non-function type 'Range<Array<Int>.Index>' (aka 'Range<Int>')
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
count += 1
}
}
return count <= 1
}
func sumArray(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element })
}
func productArray(arr: [Int]) -> Int {
return arr.reduce(1, \(product, element) { product * element })
}
func averageArray(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count
}
func maxArray(arr: [Int]) -> Int? {
return arr.max()
}
func minArray(arr: [Int]) -> Int? {
return arr.min()
}
func sumOfEven(arr: [Int]) -> Int {
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element })
}
func sumOfOdd(arr: [Int]) -> Int {
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element })
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
count += 1
}
}
return count <= 1
}
// 10. Write a function that takes an array of integers as input and returns the
// sum of all the elements in the array.
// Example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, -2, -3, -4, -5]) == -15
// sumArray([]) == 0
func sumArray(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element })
}
// 11. Write a function that takes an array of integers as input and returns the
// product of all the elements in the array.
// Example:
// productArray([1, 2, 3, 4, 5]) == 120
// productArray([-1, -2, -3, -4, -5]) == 120
// productArray([]) == 1
func productArray(arr: [Int]) -> Int {
return arr.reduce(1, \(product, element) { product * element })
}
// 12. Write a function that takes an array of integers as input and returns the
// average of all the elements in the array.
// Example:
// averageArray([1, 2, 3, 4, 5]) == 3
// averageArray([-1, -2, -3, -4, -5]) == -3
// averageArray([]) == 0
func averageArray(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count
}
// 13. Write a function that takes an array of integers as input and returns the
// maximum element in the array.
// Example:
// maxArray([1, 2, 3, 4, 5]) == 5
// maxArray([-1, -2, -3, -4, -5]) == -1
// maxArray([]) == nil
func maxArray(arr: [Int]) -> Int? {
return arr.max()
}
// 14. Write a function that takes an array of integers as input and returns the
// minimum element in the array.
// Example:
// minArray([1, 2, 3, 4, 5]) == 1
// minArray([-1, -2, -3, -4, -5]) == -5
// minArray([]) == nil
func minArray(arr: [Int]) -> Int? {
return arr.min()
}
// 15. Write a function that takes an array of integers as input and returns the
// sum of all even numbers in the array.
// Example:
// sumOfEven([1, 2, 3, 4, 5]) == 6
// sumOfEven([-1, -2, -3, -4, -5]) == -6
// sumOfEven([]) == 0
func sumOfEven(arr: [Int]) -> Int {
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element })
}
// 16. Write a function that takes an array of integers as input and returns the
// sum of all odd numbers in the array.
// Example:
// sumOfOdd([1, 2, 3, 4, 5]) == 9
// sumOfOdd([-1, -2, -3, -4, -5]) == -9
// sumOfOdd([]) == 0
func sumOfOdd(arr: [Int]) -> Int {
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element })
}
// 17. Write a function that takes an array of integers as input and returns the
// sum of all numbers in the array that are divisible by 3.
// Example:
// sumOfDivisibleBy3([1, 2, 3, 4, 5]) == 3
// sumOfDivisible
return arr.reduce(0, \(sum, element) { sum + element }) // expected ',' separator
return arr.reduce(0, \(sum, element) { sum + element }) // extra argument in call
return arr.reduce(0, \(sum, element) { sum + element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return arr.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.reduce(0, \(sum, element) { sum + element }) // string interpolation can only appear inside a string literal
return arr.reduce(1, \(product, element) { product * element }) // cannot find 'product' in scope
return arr.reduce(1, \(product, element) { product * element }) // expected ',' separator
return arr.reduce(1, \(product, element) { product * element }) // string interpolation can only appear inside a string literal
return arr.reduce(1, \(product, element) { product * element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return arr.reduce(1, \(product, element) { product * element }) // cannot find 'element' in scope
return arr.reduce(1, \(product, element) { product * element }) // extra argument in call
return arr.reduce(1, \(product, element) { product * element }) // cannot find 'product' in scope
return arr.reduce(1, \(product, element) { product * element }) // cannot find 'element' in scope
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // cannot find 'element' in scope
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // cannot find 'sum' in scope
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // extra argument in call
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // expected ',' separator
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // string interpolation can only appear inside a string literal
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // cannot find 'sum' in scope
return arr.reduce(0, \(sum, element) { sum + element }) / arr.count // cannot find 'element' in scope
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // expected ',' separator
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // extra argument in call
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.filter { element in element % 2 == 0 }.reduce(0, \(sum, element) { sum + element }) // string interpolation can only appear inside a string literal
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'sum' in scope
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // cannot find 'element' in scope
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // expected ',' separator
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // cannot convert value of type 'WritableKeyPath<_, _>' to expected argument type '(Int, Int) throws -> Int'
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // extra argument in call
return arr.filter { element in element % 2 != 0 }.reduce(0, \(sum, element) { sum + element }) // string interpolation can only appear inside a string literal
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var result = true
for i in arr {
if i == 1 {
count += 1
}
}
if count == 0 {
result = true
} else if count == 1 {
result = true
} else if count == 2 {
result = true
} else if count == 3 {
result = true
} else if count == 4 {
result = true
} else if count == 5 {
result = true
} else if count == 6 {
result = true
} else if count == 7 {
result = true
} else if count == 8 {
result = true
} else if count == 9 {
result = true
} else if count == 10 {
result = true
} else if count == 11 {
result = true
} else if count == 12 {
result = true
} else if count == 13 {
result = true
} else if count == 14 {
result = true
} else if count == 15 {
result = true
} else if count == 16 {
result = true
} else if count == 17 {
result = true
} else if count == 18 {
result = true
} else if count == 19 {
result = true
} else if count == 20 {
result = true
} else if count == 21 {
result = true
} else if count == 22 {
result = true
} else if count == 23 {
result = true
} else if count == 24 {
result = true
} else if count == 25 {
result = true
} else if count == 26 {
result = true
} else if count == 27 {
result = true
} else if count == 28 {
result = true
} else if count == 29 {
result = true
} else if count == 30 {
result = true
} else if count == 31 {
result = true
} else if count == 32 {
result = true
} else if count == 33 {
result = true
} else if count == 34 {
result = true
} else if count == 35 {
result = true
} else if count == 36 {
result = true
} else if count == 37 {
result = true
} else if count == 38 {
result = true
} else if count == 39 {
result = true
} else if count == 40 {
result = true
} else if count == 41 {
result = true
} else if count == 42 {
result = true
} else if count == 43 {
result = true
} else if count == 44 {
result = true
} else if count == 45 {
result = true
} else if count == 46 {
result = true
} else if count == 47 {
result = true
} else if count == 48 {
result = true
} else if count == 49 {
result = true
} else if count == 50 {
result = true
} else if count == 51 {
result = true
} else if count == 52 {
result = true
} else if count == 53 {
result = true
} else if count == 54 {
result = true
} else if count == 55 {
result = true
} else if count == 56 {
result = true
} else if count == 57 {
result = true
} else if count == 58 {
result = true
} else if count == 59 {
result = true
} else if count == 60 {
result = true
} else if count == 61 {
result = true
} else
XCTAssertTrue(moveOneBall(arr: [3, 4, 5, 1, 2]) == true) // cannot find 'moveOneBall' in scope
XCTAssertTrue(moveOneBall(arr: [3, 5, 10, 1, 2]) == true) // cannot find 'moveOneBall' in scope
XCTAssertTrue(moveOneBall(arr: [4, 3, 1, 2]) == false) // cannot find 'moveOneBall' in scope
XCTAssertTrue(moveOneBall(arr: [3, 5, 4, 1, 2]) == false) // cannot find 'moveOneBall' in scope
XCTAssertTrue(moveOneBall(arr: [] as [Int]) == true) // cannot find 'moveOneBall' in scope
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
sorted = false
count += 1
arr.swap(i, i-1)
}
}
}
return count <= 1
}
struct moveOneBall_Solution {
static func main() {
print(moveOneBall(arr: [3, 4, 5, 1, 2]))
print(moveOneBall(arr: [3, 5, 4, 1, 2]))
}
}
public func moveOneBall(_ arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
sorted = false
count += 1
arr.swap(i, i-1)
}
}
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
sorted = false
count += 1
arr.swap(i, i-1)
}
}
}
return count <= 1
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct moveOneBall_Solution {
static func main() {
print(moveOneBall(arr: [3, 4, 5, 1, 2]))
print(moveOneBall(arr: [3, 5, 4, 1, 2]))
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
public func moveOneBall(_ arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 1..<arr.count {
if arr[i] < arr[i-1] {
sorted = false
count += 1
arr.swap(i, i-1)
}
}
}
return count <= 1
}<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time
// complexity?
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
arr.swap(i, i-1) // value of type '[Int]' has no member 'swap'
arr.swap(i, i-1) // value of type '[Int]' has no member 'swap'
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
sorted = false
arr[i], arr[i+1] = arr[i+1], arr[i]
count += 1
}
}
}
return count <= 1
}
func sumOfEvens(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOdds(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 2 != 0 {
sum += i
}
}
return sum
}
func sumOfDivisibleByThree(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 3 == 0 {
sum += i
}
}
return sum
}
func sumOfDivisibleByFive(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 5 == 0 {
sum += i
}
}
return sum
}
func sumOfDivisibleBySeven(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 7 == 0 {
sum += i
}
}
return sum
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
sorted = false
arr[i], arr[i+1] = arr[i+1], arr[i]
count += 1
}
}
}
return count <= 1
}
// 10. Write a function that takes an array of integers and returns the sum of
// all the even numbers in the array.
// Example:
// sumOfEvens([1, 2, 3, 4, 5, 6]) == 12
// sumOfEvens([1, 3, 5, 7, 9]) == 0
func sumOfEvens(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 2 == 0 {
sum += i
}
}
return sum
}
// 11. Write a function that takes an array of integers and returns the sum of
// all the odd numbers in the array.
// Example:
// sumOfOdds([1, 2, 3, 4, 5, 6]) == 15
// sumOfOdds([1, 3, 5, 7, 9]) == 25
func sumOfOdds(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 2 != 0 {
sum += i
}
}
return sum
}
// 12. Write a function that takes an array of integers and returns the sum of
// all the numbers in the array that are divisible by 3.
// Example:
// sumOfDivisibleByThree([1, 2, 3, 4, 5, 6]) == 9
// sumOfDivisibleByThree([1, 3, 5, 7, 9]) == 0
func sumOfDivisibleByThree(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 3 == 0 {
sum += i
}
}
return sum
}
// 13. Write a function that takes an array of integers and returns the sum of
// all the numbers in the array that are divisible by 5.
// Example:
// sumOfDivisibleByFive([1, 2, 3, 4, 5, 6]) == 15
// sumOfDivisibleByFive([1, 3, 5, 7, 9]) == 0
func sumOfDivisibleByFive(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 5 == 0 {
sum += i
}
}
return sum
}
// 14. Write a function that takes an array of integers and returns the sum of
// all the numbers in the array that are divisible by 7.
// Example:
// sumOfDivisibleBySeven([1, 2, 3, 4, 5, 6]) == 21
// sumOfDivisibleBySeven([1, 3, 5, 7, 9]) == 0
func sumOfDivisibleBySeven(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 7 == 0 {
sum += i
}
}
return sum
}
// 15. Write a function that takes an array of integers and returns the sum of
// all the numbers in the array that are divisible by 11.
// Example:
// sumOfDivisibleByEleven([1, 2, 3, 4, 5, 6]) == 22
// sumOfDivisibleByEleven([1, 3, 5, 7, 9]) == 0
func sumOfDivisibleByEleven(arr: [Int]) -> Int {
var sum = 0
for i in arr {
if i % 11 == 0 {
var count = 0 // variable 'count' was never mutated; consider changing to 'let' constant
arr[i], arr[i+1] = arr[i+1], arr[i] // expected expression
arr[i], arr[i+1] = arr[i+1], arr[i] // expression of type 'Int' is unused
arr[i], arr[i+1] = arr[i+1], arr[i] // consecutive statements on a line must be separated by ';'
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i+1] {
count += 1
}
i += 1
}
return count <= 1
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var i = 0
var j = 0
while i < nums.count {
j = i + 1
while j < nums.count {
if nums[i] + nums[j] == target {
return [i, j]
}
j += 1
}
i += 1
}
return []
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i+1] {
count += 1
}
i += 1
}
return count <= 1
}
// 2. Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time
// complexity?
func twoSum(nums: [Int], target: Int) -> [Int] {
var i = 0
var j = 0
while i < nums.count {
j = i + 1
while j < nums.count {
if nums[i] + nums[j] == target {
return [i, j]
}
j += 1
}
i += 1
}
return []
}
// 3. Given an integer array nums, return the number of all the arithmetic
// subsequences of nums.
// A sequence of numbers is called arithmetic if it consists of at least three
// elements and if the difference between any two consecutive elements is the same.
// For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic
// sequences.
// For example, [1, 1, 2, 4, 4] is not an arithmetic sequence.
// A subsequence of an array is a sequence that can be formed by removing some
// elements (possibly none) of the array.
// For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].
// The answer for the given input array will fit in 32-bit signed integer.
// Example 1:
// Input: nums = [2,4,6,8,10]
// Output: 7
// Explanation: All arithmetic subsequence slices are:
// [2,4,6]
// [4,6,8]
// [6,8,10]
// [2,4,6,8]
// [4,6,8,10]
// [2,4,6,8,10]
// Example 2:
// Input: nums = [7,7,7,7,7]
// Output: 16
// Explanation: Any subsequence of this array is arithmetic.
// Constraints:
// 1 <= nums.length <= 1000
// -231 <= nums[i] <= 231 - 1
// Accepted
// 123,319
// Submissions
// 246,920
func numberOfArithmeticSlices(nums: [Int]) -> Int {
var count = 0
var i = 0
while i < nums.count {
var j = i + 1
var diff = nums[i] - nums[i+1]
while j < nums.count {
if nums[j] - nums[j-1] == diff {
count += 1
}
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
sorted = false
count += 1
var temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
}
}
}
return count <= 1
}
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
func reversePairs(nums: [Int]) -> Int {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<nums.count-1 {
if nums[i] > 2 * nums[i+1] {
sorted = false
count += 1
var temp = nums[i]
nums[i] = nums[i+1]
nums[i+1] = temp
}
}
}
return count
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<arr.count-1 {
if arr[i] > arr[i+1] {
sorted = false
count += 1
var temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
}
}
}
return count <= 1
}
// 2.
// Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example 1:
// Input: nums = [1,2,3,1,1,3]
// Output: 4
// Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
// Example 2:
// Input: nums = [1,1,1,1]
// Output: 6
// Explanation: Each pair in the array are good.
// Example 3:
// Input: nums = [1,2,3]
// Output: 0
// Explanation: There are no good pairs.
// Constraints:
// 1 <= nums.length <= 100
// 1 <= nums[i] <= 100
func numIdenticalPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] == nums[j] {
count += 1
}
}
}
return count
}
// 3.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 *
// nums[j].
// Example 1:
// Input: nums = [1,3,2,3,1]
// Output: 2
// Example 2:
// Input: nums = [2,4,3,5,1]
// Output: 3
// Constraints:
// 1 <= nums.length <= 5 * 104
// -231 <= nums[i] <= 231 - 1
func reversePairs(nums: [Int]) -> Int {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<nums.count-1 {
if nums[i] > 2 * nums[i+1] {
sorted = false
count += 1
var temp = nums[i]
nums[i] = nums[i+1]
nums[i+1] = temp
}
}
}
return count
}
// 4.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 *
// nums[j].
// Example 1:
// Input: nums = [1,3,2,3,1]
// Output: 2
// Example 2:
// Input: nums = [2,4,3,5,1]
// Output: 3
// Constraints:
// 1 <= nums.length <= 5 * 104
// -231 <= nums[i] <= 231 - 1
func reversePairs(nums: [Int]) -> Int {
var count = 0
var sorted = false
while !sorted {
sorted = true
for i in 0..<nums.count-1 {
if nums[i] > 2 * nums[i+1] {
sorted = false
count += 1
var temp
arr[i] = arr[i+1] // cannot assign through subscript: 'arr' is a 'let' constant
arr[i+1] = temp // cannot assign through subscript: 'arr' is a 'let' constant
nums[i] = nums[i+1] // cannot assign through subscript: 'nums' is a 'let' constant
nums[i+1] = temp // cannot assign through subscript: 'nums' is a 'let' constant
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty {
return true
}
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
i += 1
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
if arr.isEmpty {
return true
}
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
count += 1
}
i += 1
}
return count <= 1
}
// 12. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
// 13. Given an integer array nums, return the number of all the arithmetic subsequences of nums.
// A sequence of numbers is called arithmetic if it consists of at least two elements and if the difference between every two consecutive elements is the same.
// For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
// For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
// A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
// For example, [2,5,10] is a subsequence of [1,2,1,2,4,10].
// The answer to the above question may be large, so you are given a 64-bit integer modulo 109 + 7.
// Example 1:
// Input: nums = [2,4,6,8,10]
// Output: 7
// Explanation: All arithmetic subsequence slices are:
// [2,4,6]
// [4,6,8]
// [6,8,10]
// [2,4,6,8]
// [4,6,8,10]
// [2,4,6,8,10]
// Example 2:
// Input: nums = [7,7,7,7,7]
// Output: 16
// Explanation: Any subsequence of this array is arithmetic.
// Constraints:
// 1 <= nums.length <= 1000
// -231 <= nums[i] <= 231 - 1
// 14. Given an integer array nums, return the number of all the arithmetic subsequences of nums.
// A sequence of numbers is called arithmetic if it consists of at least two elements and if the difference between every two consecutive elements is the same.
// For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
// For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
// A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
// For example, [2,5,10] is a subsequence of [1,2,1,2,4,10].
// The answer to the above question may be large, so you are given a 64-bit integer modulo 109 + 7.
// Example 1:
// Input: nums = [2,4
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in arr {
if i > arr[0] {
count += 1
}
}
if count == 0 {
return true
}
return false
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in arr {
if i > arr[0] {
count += 1
}
}
if count == 0 {
return true
}
return false
}
// 12. Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time
// complexity?
// 13. Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time
// complexity?
// 14. Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
// Output: [0,1]
// Output: Because nums[0] + nums[1] == 9, we return [0, 1].
// Example 2:
// Input: nums = [3,2,4], target = 6
// Output: [1,2]
// Example 3:
// Input: nums = [3,3], target = 6
// Output: [0,1]
// Constraints:
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// Only one valid answer exists.
// Follow-up: Can you come up with an algorithm that is less than O(n2) time
// complexity?
// 15. Given an array of integers nums and an integer target, return indices of the
// two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// You can return the answer in any order.
// Example 1:
// Input: nums = [2,7,11,15], target = 9
//
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i+1] {
count += 1
}
i += 1
}
return count <= 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
var i = 0
while i < arr.count {
if arr[i] > arr[i+1] {
count += 1
}
i += 1
}
return count <= 1
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of integers and returns the sum of
// all the integers that are divisible by 3, 5, or 7.
// For Example:
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 23
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) ==
// 45
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) ==
// 60
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) ==
// 84
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18]) == 105
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19]) == 126
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20]) == 150
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20, 21]) == 175
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20, 21, 22]) == 201
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20, 21, 22, 23]) == 231
// sumOfDivisibleNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
// 18, 19, 20, 21, 22, 23, 24]) == 265
// sumOf
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count += 1
}
}
if count == lst1.count {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// 1.1.2.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var count = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count -= 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var count = 0
for i in lst1 {
if i % 2 == 0 {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
count -= 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1Even = 0
var lst2Even = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1Even += 1
}
if lst2[i] % 2 == 0 {
lst2Even += 1
}
}
if lst1Even == lst2Even {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1Even = 0
var lst2Even = 0
for i in 0..<lst1.count {
if lst1[i] % 2 == 0 {
lst1Even += 1
}
if lst2[i] % 2 == 0 {
lst2Even += 1
}
}
if lst1Even == lst2Even {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
result = "NO"
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
result = "NO"
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1 = lst1.filter({$0 % 2 == 0})
var lst2 = lst2.filter({$0 % 2 == 0})
if lst1.count == lst2.count {
return "YES"
} else {
return "NO"
}
}
func removeVowels(s: String) -> String {
var s = s
var s = s.replace("a", "")
var s = s.replace("e", "")
var s = s.replace("i", "")
var s = s.replace("o", "")
var s = s.replace("u", "")
return s
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1 = lst1.filter({$0 % 2 == 0})
var lst2 = lst2.filter({$0 % 2 == 0})
if lst1.count == lst2.count {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// 1.2.10
// -----------------------------------------------------------------------------
// In this problem, you will implement a function that takes a string and
// returns a new string with all the vowels removed.
// For example:
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(s: String) -> String {
var s = s
var s = s.replace("a", "")
var s = s.replace("e", "")
var s = s.replace("i", "")
var s = s.replace("o", "")
var s = s.replace("u", "")
return s
}
// -----------------------------------------------------------------------------
// 1.2.11
// -----------------------------------------------------------------------------
// In this problem, you will implement a function that takes a string and
// returns a new string with all the vowels removed.
// For example:
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(s: String) -> String {
var s = s
var s = s.replace("a", "")
var s = s.replace("e", "")
var s = s.replace("i", "")
var s = s.replace("o", "")
var s = s.replace("u", "")
return s
}
// -----------------------------------------------------------------------------
// 1.2.12
// -----------------------------------------------------------------------------
// In this problem, you will implement a function that takes a string and
// returns a new string with all the vowels removed.
// For example:
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("hello world") == "hll wrld"
func removeVowels(s: String) -> String {
var s = s
var s = s.replace("a", "")
var s = s.replace("e", "")
var s = s.replace("i", "")
var s = s.replace("o", "")
var s = s.replace("u", "")
return s
}
// -----------------------------------------------------------------------------
// 1.2.13
// -----------------------------------------------------------------------------
// In this problem, you will implement a function that takes a string and
// returns a new string with all the vowels removed.
// For example:
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqr
var lst1 = lst1.filter({$0 % 2 == 0}) // invalid redeclaration of 'lst1'
var lst2 = lst2.filter({$0 % 2 == 0}) // invalid redeclaration of 'lst2'
var s = s.replace("a", "") // missing argument label 'with:' in call
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1 = lst1.filter { $0 % 2 == 0 }
var lst2 = lst2.filter { $0 % 2 == 0 }
if lst1.count == lst2.count {
return "YES"
} else {
return "NO"
}
}
func removeSpaces(str: String) -> String {
return str.replace(" ", "")
}
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var lst1 = lst1.filter { $0 % 2 == 0 }
var lst2 = lst2.filter { $0 % 2 == 0 }
if lst1.count == lst2.count {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// with all the spaces removed.
// For example:
// removeSpaces("Hello world") == "Helloworld"
func removeSpaces(str: String) -> String {
return str.replace(" ", "")
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// For example:
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string
// with all the vowels
var lst1 = lst1.filter { $0 % 2 == 0 } // invalid redeclaration of 'lst1'
var lst2 = lst2.filter { $0 % 2 == 0 } // invalid redeclaration of 'lst2'
return str.replace(" ", "") // cannot use mutating member on immutable value: 'str' is a 'let' constant
return str.replace(" ", "") // missing argument label 'with:' in call
return str.replace(" ", "") // cannot convert return expression of type '()' to return type 'String'
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // value of tuple type '()' has no member 'replace'
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // cannot use mutating member on immutable value: 'str' is a 'let' constant
return str.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "") // missing argument label 'with:' in call
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
result = "NO"
break
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
result = "NO"
break
}
}
return result
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var result = "YES"
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
result = "NO"
break
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
result = "NO"
break
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
var count = 0
for i in lst1 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
for i in lst2 {
if i % 2 == 0 {
continue
} else {
count += 1
}
}
if count == 0 {
return "YES"
} else {
return "NO"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
var lst1 = lst1 // variable 'lst1' was never mutated; consider changing to 'let' constant
var lst2 = lst2 // variable 'lst2' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
if lst1.count != lst2.count {
return "NO"
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
if lst1.count != lst2.count {
return "NO"
}
for i in 0..<lst1.count {
if lst1[i] % 2 != 0 {
return "NO"
}
}
for i in 0..<lst2.count {
if lst2[i] % 2 != 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict.keys.contains(i) {
dict[i] += 1
} else {
dict[i] = 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict.keys.contains(i) {
dict[i] += 1
} else {
dict[i] = 1
}
}
return dict
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------
if dict.keys.contains(i) { // instance method 'contains' requires the types 'Dictionary<String, Int>.Keys.Element' (aka 'String') and 'Substring.Element' (aka 'Character') be equivalent
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i] + 1
}
}
return dict
}
func numberOfVowels(string: String) -> Int {
var count = 0
for i in string {
if i == "a" || i == "e" || i == "i" || i == "o" || i == "u" {
count += 1
}
}
return count
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i] + 1
}
}
return dict
}
// 10. Write a function that takes a string as parameter and returns the number of
// vowels contained in the string.
// Note: As the letter `y` is not considered a vowel, do not count it when
// counting the number of vowels.
// Example:
// numberOfVowels("Celebration") == 5
// numberOfVowels("Palm") == 1
func numberOfVowels(string: String) -> Int {
var count = 0
for i in string {
if i == "a" || i == "e" || i == "i" || i == "o" || i == "u" {
count += 1
}
}
return count
}
// 11. Write a function that takes a string as parameter and returns the number of
// words contained in the string.
// Note: A word is defined as a sequence of non-space characters.
// Example:
// numberOfWords("Hello world") == 2
// numberOfWords("Hi") == 1
// numberOfWords("Hi!") == 1
// numberOfWords("Hi! Hi!") == 2
// numberOfWords("Hi! Hi! Hi!") == 3
// numberOfWords("Hi Hi! Hi!") == 2
// numberOfWords("Hi! !Hi Hi!") == 2
// numberOfWords("Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
// numberOfWords("Hi! !Hi! Hi!") == 2
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = dict[i] + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = dict[i] + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = dict[i] + 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dictionary = [String : Int]()
for i in array {
if dictionary.keys.contains(i) {
dictionary[i]! += 1
} else {
dictionary[i] = 1
}
}
return dictionary
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dictionary = [String : Int]()
for i in array {
if dictionary.keys.contains(i) {
dictionary[i]! += 1
} else {
dictionary[i] = 1
}
}
return dictionary
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------
if dictionary.keys.contains(i) { // instance method 'contains' requires the types 'Dictionary<String, Int>.Keys.Element' (aka 'String') and 'Substring.Element' (aka 'Character') be equivalent
dictionary[i]! += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dictionary[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var arr = test.split(" ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i] + 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var arr = test.split(" ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] = dict[i] + 1
}
}
return dict
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Given a string, return a new string with all the vowels removed.
// Example:
// noVowels("Lambda School is awesome!") == "Lmbd Schl s wsm!"
// noVowels("aeiou") == ""
// noVowels("aeiouAEIOU") == ""
// noVowels("aEAeuUInOeO") == ""
// noVowels("aAbcDeFg") == "bcdFg"
// noVowels("") == ""
// noVowels("aeiouAEIOU12345") == "12345"
// noVowels("aAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaAaA
var arr = test.split(" ") // no exact matches in call to instance method 'split'
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var arr = test.split(separator: " ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
var arr = test.split(separator: " ")
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let dict = [:]
let array = test.split(separator: " ")
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let dict = [:]
let array = test.split(separator: " ")
for i in array {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------
let dict = [:] // empty collection literal requires an explicit type
dict[i] = 1 // cannot assign through subscript: 'dict' is a 'let' constant
dict[i] += 1 // cannot convert value of type 'Any?' to expected argument type 'Int'
return dict // cannot convert return expression of type '[AnyHashable : Any]' to return type '[String : Int]'
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let arr = test.split(separator: " ").map { $0 }
var dict = [String : Int]()
for i in arr {
if dict[i] == nil {
dict[i] = 1
} else {
dict[i] += 1
}
}
return dict
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if dict[i] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[i] += 1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dict[i] += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
// Task
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Solution
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// Time Complexity: O(n)
// Space Complexity: O(n)
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with a count of 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with a count of 1.
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
// Task
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does not matter.
// You are given a string s.
// Your task is to check if the string is balanced or not.
// A string is balanced if every open parenthesis has a corresponding close parenthesis in the string.
// The order of the parenthesis does
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and exclamation marks.
// Task
// Given an array of integers , Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
// Notes
// Array/list size is at least 2.
// Array/list numbers could be a mixture of positives, negatives also zeroes .
// Input >> Output Examples
// adjacentElementsProduct([1, 2, 3, 4, 5]) ==> output should be 120 (i.e. 2 * 3)
// adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]) ==> output should be 5000 (i.e. 5 * 24)
// adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -27, -6]) ==> output should be 329 * -27 == -861
// Task
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Task
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Task
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Task
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
// Task
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(reversed(result)))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(reversed(result)))
}
// Task
// You are given a string s and an integer k. You have to find the length of the longest substring in the string s such that the frequency of each character in this substring is less than or equal to k.
// Example
// longestSubstring(s: "ababbc", k: 2) == 5
// longestSubstring(s: "aaabb", k: 3) == 6
// longestSubstring(s: "aaabb", k: 0) == 3
// longestSubstring(s: "abcde", k: 2) == 2
// longestSubstring(s: "abcde", k: 1) == 5
// longestSubstring(s: "abcde", k: 4) == 5
// longestSubstring(s: "abcde", k: 5) == 5
// longestSubstring(s: "abcde", k: 6) == 5
// longestSubstring(s: "abcde", k: 7) == 5
// longestSubstring(s: "abcde", k: 8) == 5
// longestSubstring(s: "abcde", k: 9) == 5
// longestSubstring(s: "abcde", k: 10) == 5
// longestSubstring(s: "abcde", k: 11) == 5
// longestSubstring(s: "abcde", k: 12) == 5
// longestSubstring(s: "abcde", k: 13) == 5
// longestSubstring(s: "abcde", k: 14) == 5
// longestSubstring(s: "abcde", k: 15) == 5
// longestSubstring(s: "abcde", k: 16) == 5
// longestSubstring(s: "abcde", k: 17) == 5
// longestSubstring(s: "abcde", k: 18) == 5
// longestSubstring(s: "abcde", k: 19) == 5
// longestSubstring(s: "abcde", k: 20) == 5
// longestSubstring(s: "abcde", k: 21) == 5
// longestSubstring(s: "abcde", k: 22) == 5
// longestSubstring(s: "abcde", k: 23) == 5
// longestSubstring(s: "abcde", k: 24) == 5
// longestSubstring(s: "abcde", k: 25) == 5
// longestSubstring(s: "abcde", k: 26) == 5
// longestSubstring(s: "abcde", k: 27) == 5
// longestSubstring(s: "abcde", k: 28) == 5
// longestSubstring(s: "abcde", k: 29) == 5
// longestSubstring(s: "abcde", k: 30) == 5
// longestSubstring(s: "abcde", k: 31) == 5
// longestSubstring(s: "abcde", k: 32) == 5
// longestSubstring(s: "abcde", k: 33) == 5
// longestSubstring(s: "abcde", k: 34) == 5
// longestSubstring(s: "abcde", k: 35) == 5
// longestSubstring(s: "abcde", k: 36) == 5
// longestSubstring(s: "abcde", k: 37) == 5
// longestSubstring(s: "abcde", k: 38) == 5
// longestSubstring(s: "abcde", k: 39) == 5
// longestSubstring(s: "abcde", k: 40) == 5
//
result += char // cannot convert value of type 'Character' to expected argument type 'String'
return (result, result == String(reversed(result))) // cannot find 'reversed' in scope
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrlldd"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// input will only contain lowercase letters, numbers, spaces and/or symbols.
// Task
// Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World") ==> "HHeelllloo WWoorrl
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count / 2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
func firstNonRepeatingCharacter(s: String) -> Int {
// Create a dictionary to store the count of each character in the string
var count = [Int: Int]()
for char in s {
// Update the count of each character in the dictionary
count[char] = count[char] ?? 0 + 1
}
// Iterate through the dictionary and find the first character with count 1
for (char, count) in count {
if count == 1 {
// Return the index of the first character with count 1
return s.firstIndex(of: char)!
}
}
// If no such character is found, return -1
return -1
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count / 2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
// Task
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Solution
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with count 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with count 1.
// Time complexity: O(n)
// Space complexity: O(n)
// Function to find the first non-repeating character in a string
func firstNonRepeatingCharacter(s: String) -> Int {
// Create a dictionary to store the count of each character in the string
var count = [Int: Int]()
for char in s {
// Update the count of each character in the dictionary
count[char] = count[char] ?? 0 + 1
}
// Iterate through the dictionary and find the first character with count 1
for (char, count) in count {
if count == 1 {
// Return the index of the first character with count 1
return s.firstIndex(of: char)!
}
}
// If no such character is found, return -1
return -1
}
// Task
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Solution
// 1. Create a dictionary to store the count of each character in the string.
// 2. Iterate through the string and update the count of each character in the dictionary.
// 3. Iterate through the dictionary and find the first character with count 1.
// 4. If no such character is found, return -1.
// 5. Otherwise, return the index of the first character with count 1.
// Time complexity: O(n)
// Space complexity: O(n)
// Function to find the first non-repeating character in a string
func firstNonRepeatingCharacter(s: String) -> Int {
// Create a dictionary to store the count of each character in the string
var count = [Int: Int]()
for char in s {
// Update the count of each character in the dictionary
count[char] = count[char] ?? 0 + 1
}
// Iterate through the dictionary and find the first character with count 1
for (char, count) in count {
if count == 1 {
// Return the index of the first character with count 1
return s.firstIndex(of: char)!
}
}
// If no such character is found, return -1
return -1
}
// Task
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Solution
// 1. Create a dictionary to store the count of each character in the string.
//
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
count[char] = count[char] ?? 0 + 1 // cannot convert value of type 'Character' to expected argument type 'Int'
count[char] = count[char] ?? 0 + 1 // cannot convert value of type 'Character' to expected argument type 'Int'
return s.firstIndex(of: char)! // cannot convert return expression of type 'String.Index' to return type 'Int'
return s.firstIndex(of: char)! // cannot convert value of type 'Int' to expected argument type 'String.Element' (aka 'Character')
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count / 2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count / 2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
break
}
}
return (result, isPalindrome)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
func vowelSubstrings(s: String) -> Int {
var result = 0
var vowels = "aeiou"
for i in 0..<s.count {
var substring = ""
for j in i..<s.count {
substring += s[j]
if vowels.contains(substring) {
result += 1
}
}
}
return result
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - 1 - i] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
// Task
// You are given a string s.
// You have to find the number of substrings of s that contain at least one vowel.
// A vowel is an aeiou character.
// Example
// s = "aeiou"
// The substrings of s are:
// "a", "e", "i", "o", "u", "ae", "ei", "io", "ou", "aei", "eio", "iou", "aeiou"
// The number of substrings that contain at least one vowel is 12.
// Function Description
// Complete the vowelSubstrings function in the editor below.
// vowelSubstrings has the following parameter(s):
// string s: a string
// Returns
// int: the number of substrings of s that contain at least one vowel
func vowelSubstrings(s: String) -> Int {
var result = 0
var vowels = "aeiou"
for i in 0..<s.count {
var substring = ""
for j in i..<s.count {
substring += s[j]
if vowels.contains(substring) {
result += 1
}
}
}
return result
}
// Task
// You are given a string s.
// You have to find the number of substrings of s that contain at least one vowel.
// A vowel is an aeiou character.
// Example
// s = "aeiou"
// The substrings of s are:
// "a", "e", "i", "o", "u", "ae", "ei", "io", "ou", "aei", "eio", "iou", "aeiou"
// The number of substrings that contain at least one vowel is 12.
// Function Description
// Complete the vowelSubstrings function in the editor below.
// vowelSubstrings has the following parameter(s):
// string s: a string
// Returns
// int: the number of substrings of s that contain at least one vowel
func vowelSubstrings(s: String) -> Int {
var result = 0
var vowels = "aeiou"
for i in 0..<s.count {
var substring = ""
for j in i..<s.count {
substring += s[j]
if vowels.contains(substring) {
result += 1
}
}
}
return result
}
// Task
// You are given a string s.
// You have to find the number of substrings of s that contain at least one vowel.
// A vowel is an aeiou character.
// Example
// s = "aeiou"
// The substrings of s are:
// "a", "e", "i", "o", "u", "ae", "ei", "io", "ou", "aei", "eio", "iou", "aeiou"
// The number of substrings that contain at least one vowel is 12.
// Function Description
// Complete the vowelSubstrings function in the editor below.
// vowelSubstrings has the following parameter(s):
// string s: a string
// Returns
// int: the number of substrings of s that contain at least one vowel
func vowelSubstrings(s: String) -> Int {
var result = 0
var vowels = "aeiou"
for i in 0..<s.count {
var substring = ""
for j in i..<s.count {
substring += s[j]
if vowels.contains(substring) {
result +=
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if result[i] != result[result.count - 1 - i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
substring += s[j] // no exact matches in call to subscript
func reverseDelete(s: String, c: String) -> (String, Bool) {
let chars = Array(s)
let cChars = Array(c)
var result = ""
var isPalindrome = true
for char in chars {
if !cChars.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - i - 1] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
let chars = Array(s)
let cChars = Array(c)
var result = ""
var isPalindrome = true
for char in chars {
if !cChars.contains(char) {
result += char
}
}
for i in 0..<result.count/2 {
if result[i] != result[result.count - i - 1] {
isPalindrome = false
}
}
return (result, isPalindrome)
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all the digits that appear in s.
// Example
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd") == 8
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all the digits that appear in s.
// Example
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd") == 8
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all the digits that appear in s.
// Example
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd") == 8
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all the digits that appear in s.
// Example
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd") == 8
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all the digits that appear in s.
// Example
// sumDigits("aa1bc2d3") == 6
// sumDigits("aa11bcd") == 8
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// Task
// You are given a string s, you have to return the sum of all
result += char // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
if result[i] != result[result.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if result[i] != result[result.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += Int(char) // no exact matches in call to initializer
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
func firstUniqChar(s: String) -> Int {
var frequency = [Int](repeating: 0, count: 26)
for char in s {
frequency[char - "a"] += 1
}
for i in 0..<s.count {
if frequency[s[i] - "a"] == 1 {
return i
}
}
return -1
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result += char
}
}
return (result, result == String(result.reversed()))
}
// Task
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// Solution
// We can use a dictionary to keep track of the frequency of each character in the string.
// Then we can iterate through the string and check if the character is not in the dictionary or if the frequency is 1.
// If it is, we can return the index of the character.
// If we reach the end of the string without finding a non-repeating character, we can return -1.
// Time complexity: O(n)
// Space complexity: O(n)
func firstUniqChar(s: String) -> Int {
var frequency = [Int](repeating: 0, count: 26)
for char in s {
frequency[char - "a"] += 1
}
for i in 0..<s.count {
if frequency[s[i] - "a"] == 1 {
return i
}
}
return -1
}
// Task
// Given a string s, find the length of the longest substring without repeating characters.
// Example 1:
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: s = "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: s = "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
// Example 4:
// Input: s = ""
// Output: 0
// Solution
// We can use a sliding window to keep track of the longest substring without repeating characters.
// We can use a dictionary to keep track of the frequency of each character in the window.
// We can use two pointers to keep track of the start and end of the window.
// We can use a variable to keep track of the length of the longest substring.
// We can use a variable to keep track of the start of the longest substring.
// We can use a variable to keep track of the end of the longest substring.
// We can use a variable to keep track of the length of the longest substring without repeating characters.
// We can use a variable to keep track of the start of the longest substring without repeating characters.
// We can use a variable to keep track of the end of the longest substring without repeating characters.
// We can use a variable to keep track of the length of the longest substring without repeating characters.
// We can use a variable to keep track of the start of the longest substring without repeating characters.
// We can use a variable to keep track of the end of the longest substring without repeating characters.
// We can use a variable to keep track of the length of the longest substring without repeating characters.
// We can use a variable to keep track of the start of the longest substring without repeating characters.
// We can use a variable to keep track of the end of the longest substring without repeating characters.
// We can use a variable to keep track of the length of the longest substring without repeating characters.
// We can use a variable to keep track of the start of the longest substring without repeating characters.
// We can use a variable to keep track of the end of the longest substring without repeating characters.
// We can use a variable to keep track of the length of the longest substring without repeating characters.
// We can use a variable to keep track of the start of the longest substring without repeating characters.
// We can use a variable to keep track of the end of the longest substring without repeating characters.
// We can use a variable to keep track of the length of the
result += char // cannot convert value of type 'Character' to expected argument type 'String'
frequency[char - "a"] += 1 // binary operator '-' cannot be applied to two 'Character' operands
if frequency[s[i] - "a"] == 1 { // binary operator '-' cannot be applied to two 'Character' operands
func oddCount(lst: [String]) -> [String] {
return lst.map { $0.count(for: .digit) % 2 == 1 ? "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." : "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." }
}
func doubleArrayValues(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map { $0.count(for: .digit) % 2 == 1 ? "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." : "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." }
}
// 2.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArrayValues(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
// 3.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 4.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 5.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 6.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 7.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 8.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 9.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 10.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 11.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 12.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func mapArray(nums: [Int]) -> [Int] {
return nums.map { $0 + 1 }
}
// 13.
return lst.map { $0.count(for: .digit) % 2 == 1 ? "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." : "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." } // cannot infer contextual base in reference to member 'digit'
return lst.map { $0.count(for: .digit) % 2 == 1 ? "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." : "the number of odd elements \($0.count)n the str\($0.count)ng \($0.count) of the \($0.count)nput." } // cannot call value of non-function type 'Int'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(char) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(char) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
// 2. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 3. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 4. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 5. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 6. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 7. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 8. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 9. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 10. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for num in lst {
result.append(num * 2)
}
return result
}
// 11. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [
if Int(char) % 2 == 1 { // no exact matches in call to initializer
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as parameter and returns a new string
// with all vowels removed.
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// ---------------------------------------------------------------------------
if char % 2 == 1 { // cannot convert value of type 'Character' to expected argument type 'Int'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
// 2. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 3. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 4. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 5. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 6. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 7. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 8. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 9. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 10. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 11. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result
if Int(j) % 2 == 1 { // no exact matches in call to initializer
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
// 2.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 3.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 4.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 5.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 6.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 7.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 8.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 9.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 10.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 11.
if Int(j) % 2 != 0 { // no exact matches in call to initializer
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for i in lst {
var count = 0
for j in i {
if Int(j) % 2 != 0 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(i) of the input.")
}
return result
}
// 2. Given an array of integers, return a new array with each value doubled.
// doubleArray([1, 2, 3]) == [2, 4, 6]
func doubleArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i * 2)
}
return result
}
// 3. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 4. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 5. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 6. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 7. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 8. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 9. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 10. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
var result = [Int]()
for i in lst {
result.append(i + 1)
}
return result
}
// 11. Given an array of integers, return a new array with each value doubled.
// mapArray([1, 2, 3]) == [2, 4, 6]
func mapArray(lst: [Int]) -> [Int] {
if Int(j) % 2 != 0 { // no exact matches in call to initializer
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = 0
for char in $0 {
if Int(char) % 2 == 1 {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
func transform(s: String) -> String {
return String(s.map {
if $0 == Character(UppercaseLetter) {
return Character(LowercaseLetter)
} else {
return Character(UppercaseLetter)
}
}).reversed().join("")
}
func getSumOfDigits(n: Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func getSumOfUniqueDigits(n: Int) -> Int {
var sum = 0
var digits = [Int]()
while n > 0 {
let digit = n % 10
if !digits.contains(digit) {
sum += digit
digits.append(digit)
}
n /= 10
}
return sum
}
func firstRecurringCharacter(s: String) -> String? {
var seen = [Character]()
for char in s {
if seen.contains(char) {
return String(char)
}
seen.append(char)
}
return nil
}
func maxChar(s: String) -> Character {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
let index = chars.index(of: char)
counts[index] += 1
}
}
var maxIndex = 0
for i in 1..<counts.count {
if counts[i] > counts[maxIndex] {
maxIndex = i
}
}
return chars[maxIndex]
}
func map(lst: [Int]) -> [Int] {
return lst.map { $0 * 2 }
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = 0
for char in $0 {
if Int(char) % 2 == 1 {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput."
}
}
// 2. Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example: "Hello world" is transformed to "wORLD hello"
// "Python is fun" is transformed to "FUN is python"
func transform(s: String) -> String {
return String(s.map {
if $0 == Character(UppercaseLetter) {
return Character(LowercaseLetter)
} else {
return Character(UppercaseLetter)
}
}).reversed().join("")
}
// 3. Given a number, replace this number with
// the sum of its digits until we get to a one digit number.
// For example:
// Given 16, return 7.
// Given 942, return 6.
// Given 132, return 6 (1 + 3 + 2 = 6).
func getSumOfDigits(n: Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// 4. Given a number, find the sum of all the unique
// digits in that number.
// For example:
// Given 1234, return 1+2+3+4=10
// Given 456, return 4+5+6=15
func getSumOfUniqueDigits(n: Int) -> Int {
var sum = 0
var digits = [Int]()
while n > 0 {
let digit = n % 10
if !digits.contains(digit) {
sum += digit
digits.append(digit)
}
n /= 10
}
return sum
}
// 5. Given a string, return the first recurring character
// in it, or null if there is no recurring character.
// For example:
// "acbbac" => "b"
// "abcdef" => null
func firstRecurringCharacter(s: String) -> String? {
var seen = [Character]()
for char in s {
if seen.contains(char) {
return String(char)
}
seen.append(char)
}
return nil
}
// 6. Given a string, return the character that is most
// commonly used in the string.
// For example:
// maxChar("abccccccde") == "c"
// maxChar("apple 1231111") == "1"
func maxChar(s: String) -> Character {
var chars = [Character]()
var counts = [Int]()
for char in s {
if !chars.contains(char) {
chars.append(char)
counts.append(1)
} else {
let index = chars.index(of: char)
counts[index] += 1
}
}
var maxIndex = 0
for i in 1..<counts.count {
if counts[i] > counts[maxIndex] {
maxIndex = i
}
}
return chars[maxIndex]
}
// 7. Given an array of integers, return a new array
// with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func map(lst: [Int]) -> [Int] {
return lst.map { $0 * 2 }
}
// 8. Given a string, return a new string with
//
if Int(char) % 2 == 1 { // no exact matches in call to initializer
if $0 == Character(UppercaseLetter) { // cannot find 'UppercaseLetter' in scope
return Character(LowercaseLetter) // cannot find 'LowercaseLetter' in scope
return Character(UppercaseLetter) // cannot find 'UppercaseLetter' in scope
}).reversed().join("") // value of type 'ReversedCollection<String>' has no member 'join'
n /= 10 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n /= 10 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
let index = chars.index(of: char) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
counts[index] += 1 // value of optional type 'Array<Character>.Index?' (aka 'Optional<Int>') must be unwrapped to a value of type 'Array<Character>.Index' (aka 'Int')
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(char) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the input.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if Int(char) % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the input.")
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---
if Int(char) % 2 == 1 { // no exact matches in call to initializer
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char % 2 == 1 {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(str) of the \(lst.count)nput.")
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
if char % 2 == 1 { // cannot convert value of type 'Character' to expected argument type 'Int'
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = 0
for char in $0 {
if Int(char) % 2 == 1 {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count) of the \(count)nput."
}
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map {
let count = 0
for char in $0 {
if Int(char) % 2 == 1 {
count += 1
}
}
return "the number of odd elements \(count)n the str\(count) of the \(count)nput."
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------
if Int(char) % 2 == 1 { // no exact matches in call to initializer
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum < minSum {
minSum = currentSum
endIndex = i
startIndex = i
}
if currentSum > 0 {
currentSum = 0
startIndex = i + 1
}
}
return minSum
}
func maxAvgSubarray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
startIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
func maxSubArrayAverage(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
startIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum < minSum {
minSum = currentSum
endIndex = i
startIndex = i
}
if currentSum > 0 {
currentSum = 0
startIndex = i + 1
}
}
return minSum
}
// 1.4
// Given an array of integers nums, find the maximum average value of any non-empty subarray of nums.
// Example
// maxAvgSubarray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666668
func maxAvgSubarray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
startIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 1.5
// Given an array of integers nums, find the maximum average value of any non-empty subarray of nums.
// Example
// maxSubArrayAverage(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666668
func maxSubArrayAverage(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
startIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 1.6
// Given an array of integers nums, find the maximum average value of any non-empty subarray of nums.
// Example
// maxSubArrayAverage(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666668
func maxSubArrayAverage(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
startIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 1.7
// Given an array of integers nums, find the maximum average value of any non-empty subarray of nums.
// Example
// maxSubArrayAverage(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666668
func maxSubArrayAverage(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
var startIndex = 0 // variable 'startIndex' was written to, but never read
var endIndex = 0 // variable 'endIndex' was written to, but never read
var maxAvg = Float.min // type 'Float' has no member 'min'
var maxAvg = Float.min // type 'Float' has no member 'min'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum >= 0 {
minSum = min(minSum, currentSum)
currentSum -= nums[start]
start += 1
}
}
return minSum
}
func longestPalindrome(s: String) -> String {
var longest = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
func maxArea(height: [Int]) -> Int {
var maxArea = 0
var left = 0
var right = height.count - 1
while left < right {
maxArea = max(maxArea, min(height[left], height[right]) * (right - left))
if height[left] < height[right] {
left += 1
} else {
right -= 1
}
}
return maxArea
}
func mergeTwoLists(list1: ListNode?, list2: ListNode?) -> ListNode? {
var dummy = ListNode(0)
var current = dummy
while list1 != nil && list2 != nil {
if list1!.val < list2!.val {
current.next = list1
list1 = list1!.next
} else {
current.next = list2
list2 = list2!.next
}
current = current.next
}
current.next = list1 ?? list2
return dummy.next
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum >= 0 {
minSum = min(minSum, currentSum)
currentSum -= nums[start]
start += 1
}
}
return minSum
}
// 2. Longest Palindromic Substring
// Given a string s, return the longest palindromic substring in s.
// Example
// longestPalindrome(s: "babad") == "bab"
// longestPalindrome(s: "cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var longest = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > longest.count {
longest = substring
}
}
}
}
return longest
}
// 3. Container With Most Water
// You are given an integer array height of length n. There are n vertical lines
// drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
// Find two lines that together with the x-axis form a container, such that the
// container contains the most water.
// Return the maximum amount of water a container can store.
// Notice that you may not slant the container.
// Example
// maxArea(height: [1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
func maxArea(height: [Int]) -> Int {
var maxArea = 0
var left = 0
var right = height.count - 1
while left < right {
maxArea = max(maxArea, min(height[left], height[right]) * (right - left))
if height[left] < height[right] {
left += 1
} else {
right -= 1
}
}
return maxArea
}
// 4. Merge Two Sorted Lists
// You are given the heads of two sorted linked lists list1 and list2.
// Merge the two lists in a one sorted list. The list should be made by splicing
// together the nodes of the first two lists.
// Return the head of the merged linked list.
// Example
// mergeTwoLists(list1: ListNode(1, ListNode(2, ListNode(4))), list2: ListNode(1, ListNode(3, ListNode(4)))) == ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(4))))))
func mergeTwoLists(list1: ListNode?, list2: ListNode?) -> ListNode? {
var dummy = ListNode(0)
var current = dummy
while list1 != nil && list2 != nil {
if list1!.val < list2!.val {
current.next = list1
list1 = list1!.next
} else {
current.next = list2
list2 = list2!.next
}
current = current.next
}
current.next = list1 ?? list2
return dummy.next
}
// 5. Reverse Linked List
// Given the head of a singly linked list, reverse the list, and return the
// reversed list.
// Example
// reverseList(ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))) == ListNode(5, ListNode(4, ListNode(3, ListNode(2, ListNode(1)))))
func reverseList(head: ListNode?) -> ListNode? {
var prev = nil
var current = head
while current != nil {
var next = current!.next
current!.next = prev
prev = current
current = next
}
return prev
var substring = s[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if substring == substring.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func mergeTwoLists(list1: ListNode?, list2: ListNode?) -> ListNode? { // cannot find type 'ListNode' in scope
func mergeTwoLists(list1: ListNode?, list2: ListNode?) -> ListNode? { // cannot find type 'ListNode' in scope
func mergeTwoLists(list1: ListNode?, list2: ListNode?) -> ListNode? { // cannot find type 'ListNode' in scope
var dummy = ListNode(0) // cannot find 'ListNode' in scope
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
func maxAvgSubArray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
for num in nums {
currentSum += num
maxAvg = max(maxAvg, currentSum / Float(nums.count))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
func maxSubArray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
func maxSubArrayLen(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// 2.
// Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxAvgSubArray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxAvgSubArray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
for num in nums {
currentSum += num
maxAvg = max(maxAvg, currentSum / Float(nums.count))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
// 3.
// Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArray(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 4.
// Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArrayLen(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 5.
// Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArrayLen(nums: [Int]) -> Float {
var maxAvg = Float.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxAvg {
maxAvg = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Float(maxAvg) / Float(endIndex - startIndex + 1)
}
// 6.
// Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
var maxAvg = Float.min // type 'Float' has no member 'min'
maxAvg = max(maxAvg, currentSum / Float(nums.count)) // binary operator '/' cannot be applied to operands of type 'Int' and 'Float'
var maxAvg = Float.min // type 'Float' has no member 'min'
var maxAvg = Float.min // type 'Float' has no member 'min'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// 2. Given an array of integers nums, find the maximum length of a subarray where
// the product of all its elements is positive.
// A subarray of an array is a consecutive subsequence of the array.
// A subarray is positive if its product is greater than 0.
// A subarray is empty if its length is 0.
// Return the maximum length of a subarray with positive product.
// Example
// maxProduct(nums: [1, -2, -3, 4]) == 4
// maxProduct(nums: [-1, -2, -3, 0, 1]) == 3
// maxProduct(nums: [-1, -2, -3, 4, 5]) == 120
// maxProduct(nums: [-1, 2]) == 2
// maxProduct(nums: [-1, 2, 3, 4]) == 24
// maxProduct(nums: [-1, 2, 3, 4, -5, -6]) == 480
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7]) == 5040
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8]) == 720
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9]) == 8160
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10]) == 10080
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11]) == 120960
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12]) == 1441280
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13]) == 16937600
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14]) == 19660800
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15]) == 22598400
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16]) == 26400000
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17]) == 302400000
// maxProduct(nums: [-1, 2, 3, 4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18]) == 3432000000
// maxProduct(nums: [-
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
func maxAvgSubArray(nums: [Int]) -> Double {
var maxAvg = Double.min
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
maxAvg = max(maxAvg, currentSum / (i + 1))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
func maxSubArray(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
maxSum = max(maxSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
func maxSubArrayLen(nums: [Int]) -> Int {
var maxLen = 0
var currentSum = 0
var start = 0
for i in nums.indices {
currentSum += nums[i]
while currentSum > 0 {
maxLen = max(maxLen, i - start + 1)
currentSum -= nums[start]
start += 1
}
}
return maxLen
}
func maxSubArrayLen(nums: [Int]) -> Int {
var maxLen = 0
var currentSum = 0
var start = 0
var minSum = 0
for i in nums.indices {
currentSum += nums[i]
while currentSum < minSum {
maxLen = max(maxLen, i - start + 1)
currentSum -= nums[start]
start += 1
}
minSum = min(minSum, currentSum)
}
return maxLen
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// 2. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxAvgSubArray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxAvgSubArray(nums: [Int]) -> Double {
var maxAvg = Double.min
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
maxAvg = max(maxAvg, currentSum / (i + 1))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
// 3. Given an array of integers nums, find the maximum average value of any
// subarray of nums.
// Example
// maxSubArray(nums: [1, 12, -5, -6, 50, 3]) == 12.0
func maxSubArray(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
for i in nums.indices {
currentSum += nums[i]
maxSum = max(maxSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
// 4. Given an array of integers nums, find the maximum average value of any
// subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 4
func maxSubArrayLen(nums: [Int]) -> Int {
var maxLen = 0
var currentSum = 0
var start = 0
for i in nums.indices {
currentSum += nums[i]
while currentSum > 0 {
maxLen = max(maxLen, i - start + 1)
currentSum -= nums[start]
start += 1
}
}
return maxLen
}
// 5. Given an array of integers nums, find the maximum average value of any
// subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 4
func maxSubArrayLen(nums: [Int]) -> Int {
var maxLen = 0
var currentSum = 0
var start = 0
var minSum = 0
for i in nums.indices {
currentSum += nums[i]
while currentSum < minSum {
maxLen = max(maxLen, i - start + 1)
currentSum -= nums[start]
start += 1
}
minSum = min(minSum, currentSum)
}
return maxLen
}
// 6. Given an array of integers nums, find the maximum average value of any
// subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 4
func maxSubArrayLen(nums: [Int]) -> Int {
var maxLen = 0
var currentSum = 0
var start = 0
var minSum = 0
for i in nums.indices {
currentSum += nums[i]
while currentSum < minSum {
maxLen = max(maxLen, i - start + 1)
currentSum -= nums[start]
start += 1
}
minSum = min(minSum, currentSum)
}
return maxLen
}
// 7. Given an array of integers nums
var maxAvg = Double.min // type 'Double' has no member 'min'
var maxSum = Double.min // type 'Double' has no member 'min'
func maxSubArrayLen(nums: [Int]) -> Int { // invalid redeclaration of 'maxSubArrayLen(nums:)'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
func maxAvgSubArray(nums: [Int]) -> Double {
var maxAvg = Double.min
var currentSum = 0
for num in nums {
currentSum += num
maxAvg = max(maxAvg, currentSum / Double(nums.count))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
func maxSubArray(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
for num in nums {
currentSum += num
maxSum = max(maxSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
func maxSubArrayLen(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum > 0 {
maxSum = max(maxSum, Double(currentSum))
currentSum -= nums[start]
start += 1
}
}
return maxSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for num in nums {
currentSum += num
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// 2. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxAvgSubArray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxAvgSubArray(nums: [Int]) -> Double {
var maxAvg = Double.min
var currentSum = 0
for num in nums {
currentSum += num
maxAvg = max(maxAvg, currentSum / Double(nums.count))
if currentSum < 0 {
currentSum = 0
}
}
return maxAvg
}
// 3. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArray(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArray(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
for num in nums {
currentSum += num
maxSum = max(maxSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
// 4. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArrayLen(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum > 0 {
maxSum = max(maxSum, Double(currentSum))
currentSum -= nums[start]
start += 1
}
}
return maxSum
}
// 5. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArrayLen(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum > 0 {
maxSum = max(maxSum, Double(currentSum))
currentSum -= nums[start]
start += 1
}
}
return maxSum
}
// 6. Given an array of integers nums, find the maximum average value of any
// non-empty subarray of nums.
// Example
// maxSubArrayLen(nums: [1, 12, -5, -6, 50, 3]) == 15.666666666666667
func maxSubArrayLen(nums: [Int]) -> Double {
var maxSum = Double.min
var currentSum = 0
var start = 0
for i in 0..<nums.count {
currentSum += nums[i]
while currentSum > 0 {
maxSum = max(maxSum, Double(currentSum))
currentSum -= nums[start]
var maxAvg = Double.min // type 'Double' has no member 'min'
maxAvg = max(maxAvg, currentSum / Double(nums.count)) // binary operator '/' cannot be applied to operands of type 'Int' and 'Double'
var maxSum = Double.min // type 'Double' has no member 'min'
var maxSum = Double.min // type 'Double' has no member 'min'
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for i in nums.enumerated() {
currentSum += i.1
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
for i in nums.enumerated() {
currentSum += i.1
minSum = min(minSum, currentSum)
if currentSum < 0 {
currentSum = 0
}
}
return minSum
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var start = 0
var end = 0
while end < nums.count {
currentSum += nums[end]
while currentSum >= 0 {
minSum = min(minSum, currentSum)
currentSum -= nums[start]
start += 1
}
end += 1
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var start = 0
var end = 0
while end < nums.count {
currentSum += nums[end]
while currentSum >= 0 {
minSum = min(minSum, currentSum)
currentSum -= nums[start]
start += 1
}
end += 1
}
return minSum
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Fatal error: Index out of range
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum < minSum {
minSum = currentSum
endIndex = i
}
if currentSum > 0 {
currentSum = 0
startIndex = i + 1
}
}
return minSum
}
func maxSubArraySum(nums: [Int]) -> Int {
var maxSum = Int.min
var currentSum = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxSum {
maxSum = currentSum
}
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
func maxAverages(nums: [Int]) -> Double {
var maxSum = Int.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxSum {
maxSum = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Double(maxSum) / (endIndex - startIndex + 1)
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum < minSum {
minSum = currentSum
endIndex = i
}
if currentSum > 0 {
currentSum = 0
startIndex = i + 1
}
}
return minSum
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.1
// Given an array of integers nums, find the maximum sum of any non-empty sub-array of nums.
// Example
// maxSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 10
// maxSubArraySum(nums: [-1, -2, -3]) == -1
func maxSubArraySum(nums: [Int]) -> Int {
var maxSum = Int.min
var currentSum = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxSum {
maxSum = currentSum
}
if currentSum < 0 {
currentSum = 0
}
}
return maxSum
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2
// Given an array of integers nums, find the maximum average value of any non-empty sub-array of nums.
// Example
// maxAverages(nums: [1, 12, -5, -6, 50, 3]) == 15.166666666666668
// maxAverages(nums: [5]) == 5
func maxAverages(nums: [Int]) -> Double {
var maxSum = Int.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxSum {
maxSum = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Double(maxSum) / (endIndex - startIndex + 1)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// Given an array of integers nums, find the maximum average value of any non-empty sub-array of nums.
// Example
// maxAverages(nums: [1, 12, -5, -6, 50, 3]) == 15.166666666666668
// maxAverages(nums: [5]) == 5
func maxAverages(nums: [Int]) -> Double {
var maxSum = Int.min
var currentSum = 0
var startIndex = 0
var endIndex = 0
for i in 0..<nums.count {
currentSum += nums[i]
if currentSum > maxSum {
maxSum = currentSum
endIndex = i
}
if currentSum < 0 {
currentSum = 0
startIndex = i + 1
}
}
return Double(maxSum) / (endIndex - startIndex + 1)
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// Given an array of integers nums, find the maximum average
var startIndex = 0 // variable 'startIndex' was written to, but never read
var endIndex = 0 // variable 'endIndex' was written to, but never read
return Double(maxSum) / (endIndex - startIndex + 1) // cannot convert value of type 'Int' to expected argument type 'Double'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if i < 0 || i >= grid.count || j < 0 || j >= grid[i].count || grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity)
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if i < 0 || i >= grid.count || j < 0 || j >= grid[i].count || grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
count += fill(grid, i, j, capacity) // missing argument labels 'grid:i:j:capacity:' in call
grid[i][j] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var water = 0
var k = i
while k < grid.count {
if grid[k][j] == 1 {
water += capacity
grid[k][j] = 0
} else {
break
}
k += 1
}
result += water
}
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
var water = 0
var k = i
while k < grid.count {
if grid[k][j] == 1 {
water += capacity
grid[k][j] = 0
} else {
break
}
k += 1
}
result += water
}
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
grid[k][j] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
var count = 1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < grid.count && y >= 0 && y < grid[x].count {
count += fill(grid, x, y, capacity)
}
}
return count
}
import Foundation
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
var count = 1
for (x, y) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] {
if x >= 0 && x < grid.count && y >= 0 && y < grid[x].count {
count += fill(grid, x, y, capacity)
}
}
return count
}
print(maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1))
print(maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2))
print(maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 임현민 on 2022/04/25.
//
import Foundation
// https://leetcode.com/problems/find-the-difference/
// 26. Remove Duplicates from Sorted Array
// Given an integer array nums sorted in non-decreasing order,
// remove the duplicates in-place such that each unique element appears only once.
// The relative order of the elements should be kept the same.
// Since it is impossible to change the length of the array in some languages,
// you must instead have the result be placed in the first part of the array nums.
// More formally, if there are k elements after removing the duplicates,
// then the first k elements of nums should hold the final result.
// It does not matter what you leave beyond the first k elements.
// Return k after placing the final result in the first k slots of nums.
// Do not allocate extra space for another array.
// You must do this by modifying the input array in-place with O(1) extra memory.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * 0 <= nums.length <= 3 * 10^4
// * -100 <= nums[i] <= 100
// * nums is sorted in non-decreasing order.
// Follow up:
// * Can you solve it using O(1) extra memory?
// 예제 1
// 예제 2
// 예제 3
// 예제 4
// 예제 5
// 예제 6
// 예제 7
// 예제 8
// 예제 9
// 예제 10
// 예제 11
// 예제 12
// 예제 13
// 예제 14
// 예제 15
// 예제 16
// 예제 17
// 예제 18
// 예제 19
// 예제 20
// 예제 21
// 예제 22
// 예제
count += fill(grid, i, j, capacity) // missing argument labels 'grid:i:j:capacity:' in call
grid[i][j] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
count += fill(grid, x, y, capacity) // missing argument labels 'grid:i:j:capacity:' in call
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
let visited = Array(repeating: Array(repeating: false, count: n), count: m)
let queue = Array<(Int, Int)>()
let result = 0
for i in 0..<m {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append((i, j))
visited[i][j] = true
}
}
}
while !queue.isEmpty {
let (x, y) = queue.popLast()!
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
let nx = x + dx
let ny = y + dy
if nx < 0 || nx >= m || ny < 0 || ny >= n || visited[nx][ny] || grid[nx][ny] == 0 {
continue
}
visited[nx][ny] = true
queue.append((nx, ny))
}
result += 1
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
let visited = Array(repeating: Array(repeating: false, count: n), count: m)
let queue = Array<(Int, Int)>()
let result = 0
for i in 0..<m {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append((i, j))
visited[i][j] = true
}
}
}
while !queue.isEmpty {
let (x, y) = queue.popLast()!
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
let nx = x + dx
let ny = y + dy
if nx < 0 || nx >= m || ny < 0 || ny >= n || visited[nx][ny] || grid[nx][ny] == 0 {
continue
}
visited[nx][ny] = true
queue.append((nx, ny))
}
result += 1
}
return result
}
struct maxFill_UnitTest {
static let test1 = Test.create(name: "Test 1", arguments: (grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1), expected: 6, function: maxFill)
static let test2 = Test.create(name: "Test 2", arguments: (grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 2), expected: 5, function: maxFill)
static let test3 = Test.create(name: "Test 3", arguments: (grid: [[0, 0, 0], [0, 0, 0]], capacity: 5), expected: 0, function: maxFill)
static let test4 = Test.create(name: "Test 4", arguments: (grid: [[0, 0, 0], [0, 0, 0]], capacity: 1), expected: 0, function: maxFill)
static let test5 = Test.create(name: "Test 5", arguments: (grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2), expected: 5, function: maxFill)
static let test6 = Test.create(name: "Test 6", arguments: (grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 1), expected: 4, function: maxFill)
static let test7 = Test.create(name: "Test 7", arguments: (grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 3), expected: 4, function: maxFill)
static let test8 = Test.create(name: "Test 8", arguments: (grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 4), expected: 4, function: maxFill)
static let test9 = Test.create(name: "Test 9", arguments: (grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1,
queue.append((i, j)) // cannot use mutating member on immutable value: 'queue' is a 'let' constant
visited[i][j] = true // cannot assign through subscript: 'visited' is a 'let' constant
let (x, y) = queue.popLast()! // cannot use mutating member on immutable value: 'queue' is a 'let' constant
queue.append((nx, ny)) // cannot use mutating member on immutable value: 'queue' is a 'let' constant
result += 1 // left side of mutating operator isn't mutable: 'result' is a 'let' constant
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
var res = 0
for i in 0..<m {
for j in 0..<n {
if grid[i][j] == 1 {
res += fill(grid, i, j, capacity)
}
}
}
return res
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
var res = 0
var q = [(i: Int, j: Int)]
while !q.isEmpty {
let (x, y) = q.popLast()
if grid[x][y] == 0 {
continue
}
grid[x][y] = 0
res += 1
if x > 0 && grid[x-1][y] == 1 {
q.append((x-1, y))
}
if x < m-1 && grid[x+1][y] == 1 {
q.append((x+1, y))
}
if y > 0 && grid[x][y-1] == 1 {
q.append((x, y-1))
}
if y < n-1 && grid[x][y+1] == 1 {
q.append((x, y+1))
}
}
return res
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
var res = 0
for i in 0..<m {
for j in 0..<n {
if grid[i][j] == 1 {
res += fill(grid, i, j, capacity)
}
}
}
return res
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
let m = grid.count
let n = grid[0].count
var res = 0
var q = [(i: Int, j: Int)]
while !q.isEmpty {
let (x, y) = q.popLast()
if grid[x][y] == 0 {
continue
}
grid[x][y] = 0
res += 1
if x > 0 && grid[x-1][y] == 1 {
q.append((x-1, y))
}
if x < m-1 && grid[x+1][y] == 1 {
q.append((x+1, y))
}
if y > 0 && grid[x][y-1] == 1 {
q.append((x, y-1))
}
if y < n-1 && grid[x][y+1] == 1 {
q.append((x, y+1))
}
}
return res
}
// 2022-07-08 15:34:18
// 1. 遍历数组,遇到1就累加,遇到0就继续遍历
// 2. 遇到1就累加,遇到0就继续遍历
// 3. 遇到1就累加,遇到0就继续遍历
// 4. 遇到1就累加,遇到0就继续遍历
// 5. 遇到1就累加,遇到0就继续遍历
// 6. 遇到1就累加,遇到0就继续遍历
// 7. 遇到1就累加,遇到0就继续遍历
// 8. 遇到1就累加,遇到0就继续遍历
// 9. 遇到1就累加,遇到0就继续遍历
// 10. 遇到1就累加,遇到0就继续遍历
// 11. 遇到1就累加,遇到0就继续遍历
// 12. 遇到1就累加,遇到0就继续遍历
// 13. 遇到1就累加,遇到0就继续遍历
// 14. 遇到1就累加,遇到0就继续遍历
// 15. 遇到1就累加,遇到0就继续遍历
// 16. 遇到1就累加,遇到0就继续遍历
// 17. 遇到1就累加,遇到0就继续遍历
// 18. 遇到1就累加,遇到0就继续遍历
// 19. 遇到1就累加,遇到0就继续遍历
// 20. 遇到1就累加,遇到0就继续遍历
// 21. 遇到1就累加,遇到0就继续遍历
// 22. 遇到1就累加,遇到0就继续遍历
// 23. 遇到1就累加,遇到0就继续遍历
// 24. 遇到1就累加,遇到0就继续遍历
// 25. 遇到1就累加,遇到0就继续遍历
// 26. 遇到1就累加,遇到0就继续遍历
// 27. 遇到1就累加,遇到0就继续遍历
// 28. 遇到1就累加,遇到0就继续遍历
// 29. 遇到1就累加,遇到0就继续遍历
// 30. 遇到1就累加,遇到0就继续遍历
// 31. 遇到1就累加,遇到0就继续遍历
// 32. 遇到1就累加,遇到0就继续遍历
// 33. 遇到1就累加,遇到0就继续遍历
// 34. 遇到1就累
res += fill(grid, i, j, capacity) // missing argument labels 'grid:i:j:capacity:' in call
var q = [(i: Int, j: Int)] // expected member name or constructor call after type name
while !q.isEmpty { // instance member 'isEmpty' cannot be used on type '[(i: Int, j: Int)]'
let (x, y) = q.popLast() // cannot reference 'mutating' method as function value
let (x, y) = q.popLast() // value of optional type '(i: Int, j: Int)?' must be unwrapped to a value of type '(i: Int, j: Int)'
let (x, y) = q.popLast() // instance member 'popLast' cannot be used on type '[(i: Int, j: Int)]'
q.append((x-1, y)) // no exact matches in call to instance method 'append'
q.append((x+1, y)) // no exact matches in call to instance method 'append'
q.append((x, y-1)) // no exact matches in call to instance method 'append'
q.append((x, y+1)) // no exact matches in call to instance method 'append'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if i < 0 || i >= grid.count || j < 0 || j >= grid[i].count || grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity)
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if i < 0 || i >= grid.count || j < 0 || j >= grid[i].count || grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
count += fill(grid, i, j, capacity) // missing argument labels 'grid:i:j:capacity:' in call
grid[i][j] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
return 1 + fill(grid, i + 1, j, capacity) + fill(grid, i - 1, j, capacity) + fill(grid, i, j + 1, capacity) + fill(grid, i, j - 1, capacity) // missing argument labels 'grid:i:j:capacity:' in call
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var queue = Queue<(Int, Int)>()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append((i, j))
}
}
}
while !queue.isEmpty {
var (x, y) = queue.pop()
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if 0 <= nx && nx < grid.count && 0 <= ny && ny < grid[nx].count && grid[nx][ny] == 0 {
grid[nx][ny] = 1
queue.append((nx, ny))
result += 1
}
}
}
return result
}
func twoSum(nums1: [Int], nums2: [Int]) -> [[Int]] {
var result = [Int]()
var result2 = [Int]()
var dict = [Int: Int]()
for i in 0..<nums1.count {
dict[nums1[i]] = 1
}
for i in 0..<nums2.count {
if dict[nums2[i]] == nil {
result.append(nums2[i])
}
}
for i in 0..<nums2.count {
if dict[nums2[i]] == nil {
result2.append(nums2[i])
}
}
return [result, result2]
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var result = 0
var queue = Queue<(Int, Int)>()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append((i, j))
}
}
}
while !queue.isEmpty {
var (x, y) = queue.pop()
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if 0 <= nx && nx < grid.count && 0 <= ny && ny < grid[nx].count && grid[nx][ny] == 0 {
grid[nx][ny] = 1
queue.append((nx, ny))
result += 1
}
}
}
return result
}
var grid = [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]]
var capacity = 1
print(maxFill(grid: grid, capacity: capacity))
var grid = [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]]
var capacity = 2
print(maxFill(grid: grid, capacity: capacity))
var grid = [[0, 0, 0], [0, 0, 0]]
var capacity = 5
print(maxFill(grid: grid, capacity: capacity))<|endoftext|>// https://leetcode.com/problems/find-the-difference-of-two-arrays/
// 1 <= nums1.length, nums2.length <= 1000
// 1 <= nums1[i], nums2[i] <= 100
// nums1 and nums2 are 1-indexed.
// You are not allowed to change the relative order of the elements.
// Return the list ans of size 2 where:
// ans[0] is a list of all distinct values in nums1 that are not present in nums2.
// ans[1] is a list of all distinct values in nums2 that are not present in nums1.
// Note that the two lists need not be in the same order as in the input.
// Example 1:
// Input: nums1 = [1,2,3], nums2 = [2,4,6]
// Output: [[1,3],[4,6]]
// Example 2:
// Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
// Output: [[3],[]]
// Constraints:
// 1 <= nums1.length, nums2.length <= 1000
// 1 <= nums1[i], nums2[i] <= 1000
// Follow up: Can you solve the problem in O(n) time complexity and O(1) space complexity?
// Solution 1
// Time complexity: O(n)
// Space complexity: O(n)
func twoSum(nums1: [Int], nums2: [Int]) -> [[Int]] {
var result = [Int]()
var result2 = [Int]()
var dict = [Int: Int]()
for i in 0..<nums1.count {
dict[nums1[i]] = 1
}
for i in 0..<nums2.count {
if dict[nums2[i]] == nil {
result.append(nums2[i])
}
}
for i in 0..<nums2.count {
if dict[nums2[i]] == nil {
result2.append(nums2[i])
}
}
return [result, result2]
}
var nums1 = [1,2,3]
var nums2 = [2,4,6]
print
var queue = Queue<(Int, Int)>() // cannot find 'Queue' in scope
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
var count = 1
for di in -1...1 {
for dj in -1...1 {
if di == 0 && dj == 0 {
continue
}
if i + di < 0 || i + di >= grid.count {
continue
}
if j + dj < 0 || j + dj >= grid[i].count {
continue
}
if grid[i + di][j + dj] == 1 {
count += fill(grid, i + di, j + dj, capacity)
}
}
}
return count
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid, i, j, capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
if grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
var count = 1
for di in -1...1 {
for dj in -1...1 {
if di == 0 && dj == 0 {
continue
}
if i + di < 0 || i + di >= grid.count {
continue
}
if j + dj < 0 || j + dj >= grid[i].count {
continue
}
if grid[i + di][j + dj] == 1 {
count += fill(grid, i + di, j + dj, capacity)
}
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
count += fill(grid, i, j, capacity) // missing argument labels 'grid:i:j:capacity:' in call
grid[i][j] = 0 // cannot assign through subscript: 'grid' is a 'let' constant
count += fill(grid, i + di, j + dj, capacity) // missing argument labels 'grid:i:j:capacity:' in call
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid: grid, i: i, j: j, capacity: capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
var count = 0
var queue = [(i: Int, j: Int)]()
queue.append((i: i, j: j))
while queue.count > 0 {
var (i, j) = queue.pop()
if grid[i][j] == 0 {
grid[i][j] = 1
count += 1
if count == capacity {
return count
}
if i > 0 {
queue.append((i: i - 1, j: j))
}
if i < grid.count - 1 {
queue.append((i: i + 1, j: j))
}
if j > 0 {
queue.append((i: i, j: j - 1))
}
if j < grid[i].count - 1 {
queue.append((i: i, j: j + 1))
}
}
}
return count
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
count += fill(grid: grid, i: i, j: j, capacity: capacity)
}
}
}
return count
}
func fill(grid: [[Int]], i: Int, j: Int, capacity: Int) -> Int {
var count = 0
var queue = [(i: Int, j: Int)]()
queue.append((i: i, j: j))
while queue.count > 0 {
var (i, j) = queue.pop()
if grid[i][j] == 0 {
grid[i][j] = 1
count += 1
if count == capacity {
return count
}
if i > 0 {
queue.append((i: i - 1, j: j))
}
if i < grid.count - 1 {
queue.append((i: i + 1, j: j))
}
if j > 0 {
queue.append((i: i, j: j - 1))
}
if j < grid[i].count - 1 {
queue.append((i: i, j: j + 1))
}
}
}
return count
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
var (i, j) = queue.pop() // value of type '[(i: Int, j: Int)]' has no member 'pop'
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var queue = Queue<(Int, Int)>()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append((i, j))
}
}
}
while !queue.isEmpty {
var size = queue.count
for _ in 0..<size {
var (x, y) = queue.pop()
if x > 0 && grid[x - 1][y] == 0 {
grid[x - 1][y] = 1
queue.append((x - 1, y))
}
if x < grid.count - 1 && grid[x + 1][y] == 0 {
grid[x + 1][y] = 1
queue.append((x + 1, y))
}
if y > 0 && grid[x][y - 1] == 0 {
grid[x][y - 1] = 1
queue.append((x, y - 1))
}
if y < grid[x].count - 1 && grid[x][y + 1] == 0 {
grid[x][y + 1] = 1
queue.append((x, y + 1))
}
}
count += 1
}
return count
}
struct maxFill_SolutionTests: XCTestCase {
func test_Example1() {
let grid = [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]]
let capacity = 1
let expected = 6
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
func test_Example2() {
let grid = [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]]
let capacity = 2
let expected = 5
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
func test_Example3() {
let grid = [[0, 0, 0], [0, 0, 0]]
let capacity = 5
let expected = 0
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
}
import Cocoa
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var count = 0
var queue = Queue<(Int, Int)>()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append((i, j))
}
}
}
while !queue.isEmpty {
var size = queue.count
for _ in 0..<size {
var (x, y) = queue.pop()
if x > 0 && grid[x - 1][y] == 0 {
grid[x - 1][y] = 1
queue.append((x - 1, y))
}
if x < grid.count - 1 && grid[x + 1][y] == 0 {
grid[x + 1][y] = 1
queue.append((x + 1, y))
}
if y > 0 && grid[x][y - 1] == 0 {
grid[x][y - 1] = 1
queue.append((x, y - 1))
}
if y < grid[x].count - 1 && grid[x][y + 1] == 0 {
grid[x][y + 1] = 1
queue.append((x, y + 1))
}
}
count += 1
}
return count
}
struct maxFill_SolutionTests: XCTestCase {
func test_Example1() {
let grid = [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]]
let capacity = 1
let expected = 6
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
func test_Example2() {
let grid = [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]]
let capacity = 2
let expected = 5
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
func test_Example3() {
let grid = [[0, 0, 0], [0, 0, 0]]
let capacity = 5
let expected = 0
let actual = maxFill(grid: grid, capacity: capacity)
XCTAssertEqual(actual, expected)
}
}<|endoftext|>//
// main.swift
// 116. Populating Next Right Pointers in Each Node
//
// Created by ynfMac on 2020/10/23.
// Copyright © 2020 ynfMac. All rights reserved.
//
import Cocoa
// https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
// You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
// struct Node {
// int val;
// Node *left;
// Node *right;
// Node *next;
// }
// Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
// Initially, all next pointers are set to NULL.
// Follow up:
// You may only use constant extra space.
// Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
// Example 1:
// Input: root = [1,2,3,4,5,6,7]
// Output: [1,#,2,3,#,4,5,6,7,#]
// Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next
var queue = Queue<(Int, Int)>() // cannot find 'Queue' in scope
struct maxFill_SolutionTests: XCTestCase { // inheritance from non-protocol type 'XCTestCase'
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
struct BinarySort {
static func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct BinarySort {
static func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct BinarySort {
static func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct BinarySort {
static func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct BinarySort {
static func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a, b) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
struct BinarySort
let aOnes = String(a).filter("1").count // cannot convert value of type 'String' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
let aOnes = String(a).filter("1").count // cannot convert value of type 'String' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a: Int, b: Int) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
func removeVowels(input: String) -> String {
return input.filter { !"aeiouAEIOU".contains(Character($0)) }
}
func firstNonRepeatingCharacter(input: String) -> Int {
var dict = [Int: Int]()
for (i, c) in input.enumerate() {
if dict[c] == nil {
dict[c] = i
} else {
dict[c] = -1
}
}
var min = Int.max
for (c, i) in dict {
if i >= 0 && i < min {
min = i
}
}
return min == Int.max ? -1 : min
}
func firstNonRepeatingCharacter(input: String) -> String? {
var dict = [Int: Int]()
for (i, c) in input.enumerate() {
if dict[c] == nil {
dict[c] = i
} else {
dict[c] = -1
}
}
var min = Int.max
for (c, i) in dict {
if i >= 0 && i < min {
min = i
}
}
return min == Int.max ? nil : String(input[min])
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { (a: Int, b: Int) -> Bool in
let aOnes = String(a).filter("1").count
let bOnes = String(b).filter("1").count
return aOnes < bOnes || (aOnes == bOnes && a < b)
})
return sorted
}
// 2.
// Given a string, return a new string with all the vowels removed.
// For example, the string "This website is for losers LOL!" would become
// "Ths wbst s fr lsrs LL!".
// Note: for this kata y isn't considered a vowel.
func removeVowels(input: String) -> String {
return input.filter { !"aeiouAEIOU".contains(Character($0)) }
}
// 3.
// Given a string, find the first non-repeating character in it and return it's
// index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
func firstNonRepeatingCharacter(input: String) -> Int {
var dict = [Int: Int]()
for (i, c) in input.enumerate() {
if dict[c] == nil {
dict[c] = i
} else {
dict[c] = -1
}
}
var min = Int.max
for (c, i) in dict {
if i >= 0 && i < min {
min = i
}
}
return min == Int.max ? -1 : min
}
// 4.
// Given a string, find the first character that is not repeated anywhere in the
// string. If there are no non-repeating characters, return null (or return
// None in Python). (If there are multiple non-repeating characters, return the
// leftmost character.)
// Examples:
// s = "abcdcaf"
// return "b"
// s = "abab"
// return null
func firstNonRepeatingCharacter(input: String) -> String? {
var dict = [Int: Int]()
for (i, c) in input.enumerate() {
if dict[c] == nil {
dict[c] = i
} else {
dict[c] = -1
}
}
var min = Int.max
for (c, i) in dict {
if i >= 0 && i < min {
min = i
}
}
return min == Int.max ? nil : String(input[min])
}
// 5.
// Given a string, find the first character that is not repeated anywhere in the
// string. If there are no non-repeating characters, return null (or return
// None in Python). (If there are multiple non-repeating characters, return the
// leftmost character.)
// Examples:
// s = "abcdcaf"
// return "b"
// s = "abab"
// return null
func firstNonRepeatingCharacter(input: String) -> String? {
var dict = [Int: Int]()
for (i, c) in input.enumerate() {
if dict[c] == nil {
dict[c] = i
} else {
dict[c] = -1
}
}
var min = Int.max
for (c, i) in dict {
if i >= 0 && i < min {
min = i
}
}
return min == Int.max ? nil : String(input[min])
}
// 6.
// Given a string, find the first character that is not repeated anywhere in the
// string. If there are no non-repeating characters, return null (or return
// None in Python). (If there are multiple non-repeating characters, return the
// leftmost character.)
// Examples:
// s = "abcdcaf"
// return "b"
// s = "abab"
// return null
func firstNonRe
let aOnes = String(a).filter("1").count // cannot convert value of type 'String' to expected argument type '(String.Element) throws -> Bool' (aka '(Character) throws -> Bool')
return input.filter { !"aeiouAEIOU".contains(Character($0)) } // missing argument label 'extendedGraphemeClusterLiteral:' in call
for (i, c) in input.enumerate() { // value of type 'String' has no member 'enumerate'
for (i, c) in input.enumerate() { // value of type 'String' has no member 'enumerate'
return min == Int.max ? nil : String(input[min]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
// 2.
// https://www.codewars.com/kata/5648b12ce6a07b5cc00004e4/train/swift
// Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
// Examples:
// Input: 42145 Output: 54421
// Input: 145263 Output: 654321
// Input: 123456789 Output: 987654321
// Note: Your function should only return the number with its digits in descending order.
// Function Description
// Complete the descendingOrder function in the editor below.
// descendingOrder has the following parameter(s):
// int n: an integer
// Returns
// int: the integer with digits in descending order
// Constraints
// 0 <= n < 1010
// Input Format For Custom Testing
// Sample Case 0
// Sample Input
// STDIN Function
// ----- --------
// 1234567890 n = 1234567890
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 1
// Sample Input
// STDIN Function
// ----- --------
// 1111111111 n = 1111111111
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 2
// Sample Input
// STDIN Function
// ----- --------
// 1000000000 n = 1000000000
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 3
// Sample Input
// STDIN Function
// ----- --------
// 10000000000 n = 10000000000
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 4
// Sample Input
// STDIN Function
// ----- --------
// 100000000000 n = 100000000000
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 5
// Sample Input
// STDIN Function
// ----- --------
// 1000000000000 n = 1000000000000
// Sample Output
// 9876543210
// Explanation
// 9876543210 is the largest number that can be formed
// with its digits in descending order.
// Sample Case 6
// Sample Input
// STDIN Function
// ----- --------
// 10000000000000 n = 10000000000000
// Sample Output
// 9876543210
// Explanation
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
// }
// 2.
// Given a string, return a new string with all the vowels removed.
// For example, say you wanted to remove all the vowels in "hello world":
// removeVowels("hello world") // "hll wrld"
// removeVowels("aaaaa") // ""
// removeVowels("") // ""
// Your solution should be case-insensitive, removing the uppercase V's.
// More info at: http://en.wikipedia.org/wiki/Vowel
// Have fun!
// function removeVowels(str) {
// return str.replace(/[aeiou]/gi, '')
// }
// 3.
// Given a string, find the first non-repeating character in it and return it's index.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// function firstUniqChar(s: String) -> Int {
// let chars = Array(s.length)
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] == nil) {
// chars[c] = i
// } else {
// chars[c] = nil
// }
// }
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] != nil) {
// return i
// }
// }
// return -1
// }
// 4.
// Given a string, find the first non-repeating character in it and return it's index.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// function firstUniqChar(s: String) -> Int {
// let chars = Array(s.length)
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] == nil) {
// chars[c] = i
// } else {
// chars[c] = nil
// }
// }
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] != nil) {
// return i
// }
// }
// return -1
// }
// 5.
// Given a string, find the first non-repeating character in it and return it's index.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
// function firstUniqChar(s: String) -> Int {
// let chars = Array(s.length)
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] == nil) {
// chars[c] = i
// } else {
// chars[c] = nil
// }
// }
// for (let i = 0; i < s.length; i++) {
// let c = s[i]
// if (chars[c] != nil) {
// return i
// }
// }
// return -1
// }
// 6.
//
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
let sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { (a: Int) -> Int in
let count = a.bitCount
return count == 0 ? 0 : count
})
}
func changeCase(str: String) -> String {
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
func doubleArray(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
func firstLast(str1: String, str2: String) -> String {
return str1.isEmpty ? str2 + "@" : str1.first! + str2.last!
}
func firstLast(str: String) -> String {
return str.isEmpty ? "" : str.subString(1, str.count - 2)
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { (a: Int) -> Int in
let count = a.bitCount
return count == 0 ? 0 : count
})
}
// }
// 2.
// 2.1
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Hello World " ==> "dLOw NOREH"
// "" ==> ""
func changeCase(str: String) -> String {
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join()
}
// 2.2
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(arr: [Int]) -> [Int] {
return arr.map { $0 * 2 }
}
// 2.3
// Given two strings, a and b, return a new string made of the first char of a and the last char of b, so "yo" and "java" yields "ya".
// If either string is length 0, use '@' for its missing char.
// For example:
// firstLast("last", "first") -> "ls"
// firstLast("yo", "java") -> "ya"
// firstLast("hi", "") -> "hi@"
// firstLast("", "coding") -> "coding@"
func firstLast(str1: String, str2: String) -> String {
return str1.isEmpty ? str2 + "@" : str1.first! + str2.last!
}
// 2.4
// Given a string, return a new string with the first and last chars removed.
// For example:
// With "Hello", return "ell".
// With "java", return "av".
// With "coding", return "odin".
// Note: strings with fewer than 2 chars should return an empty string.
// For example:
// firstLast("Hello") -> "ell"
// firstLast("java") -> "av"
// firstLast("coding") -> "odin"
// firstLast("code") -> ""
// firstLast("") -> ""
func firstLast(str: String) -> String {
return str.isEmpty ? "" : str.subString(1, str.count - 2)
}
// 2.5
// Given a string, return a new string with the first and last chars removed.
// For example:
// With "Hello", return "ell".
// With "java", return "av".
// With "coding", return "odin".
// Note: strings with fewer than 2 chars should return an empty string.
// For example:
// firstLast("Hello") -> "ell"
// firstLast("java") -> "av"
// firstLast("coding") -> "odin"
// firstLast("code") -> ""
// firstLast("") -> ""
func firstLast(str: String) -> String {
return str.isEmpty ? "" : str.subString(1, str.count - 2)
}
// 2.6
// Given a string, return a new string with the first and last chars removed.
// For example:
// With "Hello", return "ell".
// With "java", return "av".
// With "coding", return "odin".
// Note: strings with fewer than 2 chars should return an empty string.
// For example:
// firstLast("Hello") -> "ell"
// firstLast("java") -> "av"
// firstLast("coding") -> "odin"
// first
return arr.sorted(by: { (a: Int) -> Int in // contextual closure type '(Int, Int) throws -> Bool' expects 2 arguments, but 1 was used in closure body
return arr.sorted(by: { (a: Int) -> Int in // declared closure result 'Int' is incompatible with contextual type 'Bool'
let count = a.bitCount // value of type 'Int' has no member 'bitCount'
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'isUpperCase'
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toLowerCase'
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'Array<_>' has no member 'join'
return str.map { $0.isUpperCase == true ? $0.toLowerCase() : $0.toUpperCase() }.join() // value of type 'String.Element' (aka 'Character') has no member 'toUpperCase'
return str1.isEmpty ? str2 + "@" : str1.first! + str2.last! // binary operator '+' cannot be applied to two 'String.Element' (aka 'Character') operands
return str1.isEmpty ? str2 + "@" : str1.first! + str2.last! // cannot convert return expression of type 'String.Element' (aka 'Character') to return type 'String'
return str.isEmpty ? "" : str.subString(1, str.count - 2) // value of type 'String' has no member 'subString'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
}
// 2.
// Given a string of words, you need to find the highest scoring word.
// Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
// For example, the score of abad is 8 (1 + 2 + 1 + 4).
// You need to return the highest scoring word as a string.
// If two words score the same, return the word that appears earliest in the original string.
// All letters will be lowercase and all inputs will be valid.
func high(s: String) -> String {
let words = s.split(separator: " ")
let scores = words.map { $0.map { $0 == "a" ? 1 : $0 == "b" ? 2 : $0 == "c" ? 3 : $0 == "d" ? 4 : $0 == "e" ? 5 : $0 == "f" ? 6 : $0 == "g" ? 7 : $0 == "h" ? 8 : $0 == "i" ? 9 : $0 == "j" ? 10 : $0 == "k" ? 11 : $0 == "l" ? 12 : $0 == "m" ? 13 : $0 == "n" ? 14 : $0 == "o" ? 15 : $0 == "p" ? 16 : $0 == "q" ? 17 : $0 == "r" ? 18 : $0 == "s" ? 19 : $0 == "t" ? 20 : $0 == "u" ? 21 : $0 == "v" ? 22 : $0 == "w" ? 23 : $0 == "x" ? 24 : $0 == "y" ? 25 : $0 == "z" ? 26 : 0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }.map { $0 == 0 ? 0 : $0 }
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
return sorted
}
// 2.
// Given a string, return a new string with all the vowels removed.
// For example, say you wanted to remove vowels from "The quick brown fox."
// Return "Th qck brwn fx.".
// The output should be case-sensitive, so "tH." wouldn't be correct.
// The output should have all the spaces, but only when they are part of the original word
// and not in the vowels.
// So "The quick brown fox." would be returned as "Th qck brwn fx.".
// Note that you can assume the input will be a valid string.
// You may not use any built-in functions that count the number of vowels in a string.
// You may use the following functions:
// countVowels(string: String) -> Int
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(string: String) -> String
// removeVowels(
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
var sorted = arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count })
}
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
// 2.
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0 < $1 : $0.binaryString.count < $1.binaryString.count }) // value of type 'Int' has no member 'binaryString'
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0.compare($1) : $0.binaryString.count < $1.binaryString.count })
}
func descendingOrder(n: Int) -> Int {
return Int(String(String(n).map(Character.init).sorted().map(String.init).joined()).reverse())
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted(by: { $0.binaryString.count == $1.binaryString.count ? $0.compare($1) : $0.binaryString.count < $1.binaryString.count })
}
// 2.
// https://www.codewars.com/kata/5648b12454c1c52400000006/train/swift
// Your task is to make a function that can take any non-negative integer as an argument
// and return it with its digits in descending order. Essentially, rearrange the digits
// to create the highest possible number.
// Examples:
// Input: 42145 Output: 54421
// Input: 145263 Output: 654321
// Input: 123456789 Output: 987654321
func descendingOrder(n: Int) -> Int {
return Int(String(String(n).map(Character.init).sorted().map(String.init).joined()).reverse())
}
// 3.
// https://www.codewars.com/kata/5648b12454c1c52400000006/train/swift
// Your task is to make a function that can take any non-negative integer as an
// argument and return it with its digits in descending order. Essentially, rearrange
// the digits to create the highest possible number.
// Examples:
// Input: 42145 Output: 54421
// Input: 145263 Output: 654321
// Input: 123456789 Output: 987654321
func descendingOrder(n: Int) -> Int {
return Int(String(String(n).map(Character.init).sorted().map(String.init).joined()).reverse())
}
// 4.
// https://www.codewars.com/kata/5648b12454c1c52400000006/train/swift
// Your task is to make a function that can take any non-negative integer as an
// argument and return it with its digits in descending order. Essentially, rearrange
// the digits to create the highest possible number.
// Examples:
// Input: 42145 Output: 54421
// Input: 145263 Output: 654321
// Input: 123456789 Output: 987654321
func descendingOrder(n: Int) -> Int {
return Int(String(String(n).map(Character.init).sorted().map(String.init).joined()).reverse())
}
// 5.
// https://www.codewars.com/kata/5648b12454c1c52400000006/train/swift
// Your task is to make a function that can take any non-negative integer as an
// argument and return it with its digits in descending order. Essentially, rearrange
// the digits to create the highest possible number.
// Examples:
// Input: 42145 Output: 54421
// Input: 145263 Output: 654321
// Input: 123456789 Output: 987654321
func descendingOrder(n: Int) -> Int {
return Int(String(String(n).map(Character.init).sorted().map(String.init).joined()).reverse())
}
// 6.
// https://www.codewars.com/kata/5648b12454c1c52400000006/train/swift
// Your task is to make a function that can take any non-negative integer as an
// argument and return it with its digits in descending order. Essentially, rearrange
// the digits to create the highest possible number.
// Examples:
// Input: 42145 Output: 5
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aOnes = binaryOnes(a)
let bOnes = binaryOnes(b)
return aOnes == bOnes ? a < b : aOnes < bOnes
}
}
private func binaryOnes(n: Int) -> Int {
var ones = 0
while n > 0 {
ones += n & 1
n >>= 1
}
return ones
}
import XCTest
class SortArrayTest: XCTestCase {
func test1() {
let arr = [1, 5, 2, 3, 4]
let expected = [1, 2, 3, 4, 5]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test2() {
let arr = [-2, -3, -4, -5, -6]
let expected = [-6, -5, -4, -3, -2]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test3() {
let arr = [1, 0, 2, 3, 4]
let expected = [0, 1, 2, 3, 4]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aOnes = binaryOnes(a)
let bOnes = binaryOnes(b)
return aOnes == bOnes ? a < b : aOnes < bOnes
}
}
private func binaryOnes(n: Int) -> Int {
var ones = 0
while n > 0 {
ones += n & 1
n >>= 1
}
return ones
}
// -----------------------------------------------------------------------------
import XCTest
class SortArrayTest: XCTestCase {
func test1() {
let arr = [1, 5, 2, 3, 4]
let expected = [1, 2, 3, 4, 5]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test2() {
let arr = [-2, -3, -4, -5, -6]
let expected = [-6, -5, -4, -3, -2]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test3() {
let arr = [1, 0, 2, 3, 4]
let expected = [0, 1, 2, 3, 4]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
}
// -----------------------------------------------------------------------------
import XCTest
class SortArrayTest: XCTestCase {
func test1() {
let arr = [1, 5, 2, 3, 4]
let expected = [1, 2, 3, 4, 5]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test2() {
let arr = [-2, -3, -4, -5, -6]
let expected = [-6, -5, -4, -3, -2]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test3() {
let arr = [1, 0, 2, 3, 4]
let expected = [0, 1, 2, 3, 4]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
}
// -----------------------------------------------------------------------------
import XCTest
class SortArrayTest: XCTestCase {
func test1() {
let arr = [1, 5, 2, 3, 4]
let expected = [1, 2, 3, 4, 5]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test2() {
let arr = [-2, -3, -4, -5, -6]
let expected = [-6, -5, -4, -3, -2]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
func test3() {
let arr = [1, 0, 2, 3, 4]
let expected = [0, 1, 2, 3, 4]
let actual = sortArray(arr: arr)
XCTAssertEqual(expected, actual)
}
}
// -----------------------------------------------------------------------------
import XCTest
class SortArrayTest: XCTestCase {
func test1() {
let arr = [1, 5, 2, 3, 4]
let expected = [1,
import XCTest // no such module 'XCTest'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(separator: " ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(separator: " ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if letter.isConsonant() { // value of type 'Substring.Element' (aka 'Character') has no member 'isConsonant'
consonants += 1 // left side of mutating operator isn't mutable: 'consonants' is a 'let' constant
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
var result = []
var count = 0
for char in s {
if !vowels.contains(char) {
count += 1
}
if count == n {
result.append(String(char))
count = 0
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let vowels = "aeiou"
var result = []
var count = 0
for char in s {
if !vowels.contains(char) {
count += 1
}
if count == n {
result.append(String(char))
count = 0
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var result = []
for i in words {
var count = 0
for j in i {
if j == "a" || j == "e" || j == "i" || j == "o" || j == "u" {
count += 1
}
}
if count == n {
result.append(i)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var result = []
for i in words {
var count = 0
for j in i {
if j == "a" || j == "e" || j == "i" || j == "o" || j == "u" {
count += 1
}
}
if count == n {
result.append(i)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
var count = 0
var result = []
for i in s.split(" ") {
for j in i {
if j == "a" || j == "e" || j == "i" || j == "o" || j == "u" {
count += 1
}
}
if count == n {
result.append(i)
}
count = 0
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var count = 0
var result = []
for i in s.split(" ") {
for j in i {
if j == "a" || j == "e" || j == "i" || j == "o" || j == "u" {
count += 1
}
}
if count == n {
result.append(i)
}
count = 0
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
for i in s.split(" ") { // no exact matches in call to instance method 'split'
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var consonants = 0
var result = []
for word in words {
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
consonants = 0
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var consonants = 0
var result = []
for word in words {
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
consonants = 0
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(" ")
var result = []
for word in words {
let consonants = 0
for letter in word {
if letter.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var consonants = 0
var result = []
for word in words {
for char in word {
if char.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
consonants = 0
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var consonants = 0
var result = []
for word in words {
for char in word {
if char.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
consonants = 0
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var result = []
for word in words {
var count = 0
for letter in word {
if letter.isConsonant() {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
extension String {
func isConsonant() -> Bool {
return !isVowel()
}
func isVowel() -> Bool {
return ["a", "e", "i", "o", "u"].contains(self)
}
}
import Foundation
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
var words = s.split(" ")
var result = []
for word in words {
var count = 0
for letter in word {
if letter.isConsonant() {
count += 1
}
}
if count == n {
result.append(word)
}
}
return result
}
extension String {
func isConsonant() -> Bool {
return !isVowel()
}
func isVowel() -> Bool {
return ["a", "e", "i", "o", "u"].contains(self)
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by Ankur Kumar Singh on 10/07/20.
// Copyright © 2020 Ankur Kumar Singh. All rights reserved.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
sum += i
}
print(sum)
var sum2 = 0
for i in array {
if i % 2 == 0 {
sum2 += i
}
}
print(sum2)
var sum3 = 0
for i in array {
if i % 2 != 0 {
sum3 += i
}
}
print(sum3)
var sum4 = 0
for i in array {
if i % 2 == 0 {
sum4 += i
} else {
sum4 -= i
}
}
print(sum4)
var sum5 = 0
for i in array {
if i % 2 == 0 {
sum5 += i
} else {
sum5 -= i
}
}
print(sum5)
var sum6 = 0
for i in array {
if i % 2 == 0 {
sum6 += i
} else {
sum6 -= i
}
}
print(sum6)
var sum7 = 0
for i in array {
if i % 2 == 0 {
sum7 += i
} else {
sum7 -= i
}
}
print(sum7)
var sum8 = 0
for i in array {
if i % 2 == 0 {
sum8 += i
} else {
sum8 -= i
}
}
print(sum8)
var sum9 = 0
for i in array {
if i % 2 == 0 {
sum9 += i
} else {
sum9 -= i
}
}
print(sum9)
var sum10 = 0
for i in array {
if i % 2 == 0 {
sum10 += i
} else {
sum10 -= i
}
}
print(sum10)
var sum11 = 0
for i in array {
if i % 2 == 0 {
sum11 += i
} else {
sum11 -= i
}
}
print(sum11)
var sum12 = 0
for i in array {
if i % 2 == 0 {
sum12 += i
} else {
sum12 -= i
}
}
print(sum12)
var sum13 = 0
for i in array {
if i % 2 == 0 {
sum13 += i
} else {
sum13 -= i
}
}
print(sum13)
var sum14 = 0
for i in array {
if i % 2 == 0 {
sum14 += i
} else {
sum14 -= i
}
}
print(sum14)
var sum15
var words = s.split(" ") // no exact matches in call to instance method 'split'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(separator: " ")
var result = []
for word in words {
let consonants = 0
for char in word {
if char.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let words = s.split(separator: " ")
var result = []
for word in words {
let consonants = 0
for char in word {
if char.isConsonant() {
consonants += 1
}
}
if consonants == n {
result.append(word)
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var result = [] // empty collection literal requires an explicit type
if char.isConsonant() { // value of type 'Substring.Element' (aka 'Character') has no member 'isConsonant'
consonants += 1 // left side of mutating operator isn't mutable: 'consonants' is a 'let' constant
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in word.reversed() {
if vowels.contains(i) {
result = i
break
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in word.reversed() {
if vowels.contains(i) {
result = i
break
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
if vowels.contains(i) { // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result = i // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var result = ""
for i in 0..<word.count {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if consonants.contains(word[i]) {
result = word[i]
break
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
var result = ""
for i in 0..<word.count {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if consonants.contains(word[i]) {
result = word[i]
break
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if vowels.contains(word[i]) { // cannot convert value of type 'Character' to expected argument type 'String'
result = word[i] // cannot assign value of type 'Character' to type 'String'
if consonants.contains(word[i]) { // cannot convert value of type 'Character' to expected argument type 'String'
result = word[i] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let vowelsSet = Set(vowels)
let wordArray = Array(word)
let wordLength = wordArray.count
let vowelIndex = -1
for i in 0..<wordLength {
let letter = wordArray[i]
if vowelsSet.contains(letter) {
vowelIndex = i
break
}
}
if vowelIndex == -1 {
return ""
}
let vowel = wordArray[vowelIndex]
let consonantIndex = -1
for i in (vowelIndex..<wordLength) {
let letter = wordArray[i]
if !vowelsSet.contains(letter) {
consonantIndex = i
break
}
}
if consonantIndex == -1 {
return ""
}
let consonant = wordArray[consonantIndex]
let closestVowel = ""
let distance = 10000
for i in (vowelIndex..<consonantIndex) {
let letter = wordArray[i]
if vowelsSet.contains(letter) {
let currentDistance = abs(i - vowelIndex)
if currentDistance < distance {
distance = currentDistance
closestVowel = letter
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
let vowelsSet = Set(vowels)
let wordArray = Array(word)
let wordLength = wordArray.count
let vowelIndex = -1
for i in 0..<wordLength {
let letter = wordArray[i]
if vowelsSet.contains(letter) {
vowelIndex = i
break
}
}
if vowelIndex == -1 {
return ""
}
let vowel = wordArray[vowelIndex]
let consonantIndex = -1
for i in (vowelIndex..<wordLength) {
let letter = wordArray[i]
if !vowelsSet.contains(letter) {
consonantIndex = i
break
}
}
if consonantIndex == -1 {
return ""
}
let consonant = wordArray[consonantIndex]
let closestVowel = ""
let distance = 10000
for i in (vowelIndex..<consonantIndex) {
let letter = wordArray[i]
if vowelsSet.contains(letter) {
let currentDistance = abs(i - vowelIndex)
if currentDistance < distance {
distance = currentDistance
closestVowel = letter
}
}
}
return closestVowel
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
vowelIndex = i // cannot assign to value: 'vowelIndex' is a 'let' constant
consonantIndex = i // cannot assign to value: 'consonantIndex' is a 'let' constant
distance = currentDistance // cannot assign to value: 'distance' is a 'let' constant
closestVowel = letter // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
closestVowel = letter // cannot assign to value: 'closestVowel' is a 'let' constant
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in word.reversed() {
if vowels.contains(i) {
result = i
break
}
}
return result
}
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in word.reversed() {
if vowels.contains(i) {
result = i
break
}
}
return result
}
// 2. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 3. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 4. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 5. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 6. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 7. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 8. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 9. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("") == ""
// alphabetSoup("a") == "a"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 10. Write a function that takes a string and returns a string with its letters in alphabetical order.
// Example:
// alphabetSoup("hello") == "ehl
if vowels.contains(i) { // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result = i // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
for i in word.reversed().enumerated() {
if vowels.contains(i.element) {
closestVowel = i.element
break
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "aeiou"
var closestVowel = ""
for i in word.reversed().enumerated() {
if vowels.contains(i.element) {
closestVowel = i.element
break
}
}
return closestVowel
}
// 10. Write a function that takes a string as an argument and returns a new string that
// contains all the vowels from the original string.
// The original string will only contain lowercase letters.
// Example:
// getVowels("apple") == "ae"
// getVowels("banana") == "aana"
// getVowels("kiwi") == "i"
// getVowels("orange") == "aoue"
// getVowels("mango") == "aou"
// getVowels("grapefruit") == "aou"
// getVowels("cherry") == "a"
// getVowels("peach") == "a"
// getVowels("pear") == "a"
// getVowels("plum") == ""
// getVowels("strawberry") == "aoue"
// getVowels("blueberry") == "aoue"
// getVowels("melon") == "aou"
// getVowels("watermelon") == "aou"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// getVowels("kiwi") == "i"
// get
closestVowel = i.element // cannot assign value of type 'ReversedCollection<String>.Element' (aka 'Character') to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in 0..<word.count {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
return result
}
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
func noSpace(word: String) -> String {
return String(word.replace(" ", ""))
}
func removeVowels(word: String) -> String {
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", ""))
}
func removeConsonants(word: String) -> String {
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "").replace("I", "").replace("O", "").replace("U", ""))
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in 0..<word.count {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if vowels.contains(word[i]) {
result = word[i]
break
}
}
return result
}
// 2. Write a function that takes a string and returns a string with the letters in
// alphabetical order.
// Example:
// alphabetSoup("hello") == "ehllo"
// alphabetSoup("edabit") == "abdeit"
// alphabetSoup("hacker") == "acehkr"
// alphabetSoup("geek") == "eegk"
// alphabetSoup("javascript") == "aacijprstv"
func alphabetSoup(word: String) -> String {
return String(word.sorted())
}
// 3. Write a function that takes a string and returns a string with all the
// spaces removed.
// Example:
// noSpace("I love dogs") == "Ilovodogs"
// noSpace("Coding is fun") == "Codingisfun"
// noSpace("Honey is sweet") == "Honeyissweet"
// noSpace(" moon is near") == "moonisnear"
func noSpace(word: String) -> String {
return String(word.replace(" ", ""))
}
// 4. Write a function that takes a string and returns a string with all the
// vowels removed.
// Example:
// removeVowels("I love coding") == "l vcdng"
// removeVowels("Hello world") == "Hll wrld"
// removeVowels("I can't sleep") == "c nt slp"
// removeVowels("Good night") == "Gd nt"
func removeVowels(word: String) -> String {
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", ""))
}
// 5. Write a function that takes a string and returns a string with all the
// consonants removed.
// Example:
// removeConsonants("I love coding") == "I lv cdng"
// removeConsonants("Hello world") == "Hll wrld"
// removeConsonants("I can't sleep") == "I nt slp"
// removeConsonants("Good night") == "Gd nt"
func removeConsonants(word: String) -> String {
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "").replace("I", "").replace("O", "").replace("U", ""))
}
// 6. Write a function that takes a string and returns a string with all the
// vowels removed.
// Example:
// removeConsonants("I love coding") == "I lv cdng"
// removeConsonants("Hello world") == "Hll wrld"
// removeConsonants("I can't sleep") == "I nt slp"
// removeConsonants("Good night") == "Gd nt"
func removeConsonants(word: String) -> String {
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "")
if vowels.contains(word[i]) { // cannot convert value of type 'Character' to expected argument type 'String'
result = word[i] // cannot assign value of type 'Character' to type 'String'
if vowels.contains(word[i]) { // cannot convert value of type 'Character' to expected argument type 'String'
result = word[i] // cannot assign value of type 'Character' to type 'String'
return String(word.replace(" ", "")) // no exact matches in call to initializer
return String(word.replace(" ", "")) // missing argument label 'with:' in call
return String(word.replace(" ", "")) // cannot use mutating member on immutable value: 'word' is a 'let' constant
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")) // cannot use mutating member on immutable value: 'word' is a 'let' constant
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")) // value of tuple type '()' has no member 'replace'
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")) // missing argument label 'with:' in call
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "").replace("I", "").replace("O", "").replace("U", "")) // cannot use mutating member on immutable value: 'word' is a 'let' constant
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "").replace("I", "").replace("O", "").replace("U", "")) // missing argument label 'with:' in call
return String(word.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "").replace("A", "").replace("E", "").replace("I", "").replace("O", "").replace("U", "")) // value of tuple type '()' has no member 'replace'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let result = ""
for i in 0..<word.count {
if word[i].isVowel() {
result = word[i]
break
}
}
for i in word.count-1...0 {
if word[i].isVowel() {
if result == "" {
result = word[i]
} else {
if (word[i].distanceFrom(result) < word[i-1].distanceFrom(result)) {
result = word[i]
}
}
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let result = ""
for i in 0..<word.count {
if word[i].isVowel() {
result = word[i]
break
}
}
for i in word.count-1...0 {
if word[i].isVowel() {
if result == "" {
result = word[i]
} else {
if (word[i].distanceFrom(result) < word[i-1].distanceFrom(result)) {
result = word[i]
}
}
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if word[i].isVowel() { // value of type 'Character' has no member 'isVowel'
result = word[i] // cannot assign to value: 'result' is a 'let' constant
result = word[i] // cannot assign value of type 'Character' to type 'String'
if word[i].isVowel() { // value of type 'Character' has no member 'isVowel'
result = word[i] // cannot assign value of type 'Character' to type 'String'
result = word[i] // cannot assign to value: 'result' is a 'let' constant
if (word[i].distanceFrom(result) < word[i-1].distanceFrom(result)) { // value of type 'Character' has no member 'distanceFrom'
if (word[i].distanceFrom(result) < word[i-1].distanceFrom(result)) { // value of type 'Character' has no member 'distanceFrom'
result = word[i] // cannot assign to value: 'result' is a 'let' constant
result = word[i] // cannot assign value of type 'Character' to type 'String'
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
result = word[i]
break
}
}
return result
}
func removeVowels(word: String) -> String {
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
continue
}
result += word[i]
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
result = word[i]
break
}
}
for i in word.count-1..<0 {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
result = word[i]
break
}
}
return result
}
// 2. Write a function that takes a string as an argument and returns a string with all
// the vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
func removeVowels(word: String) -> String {
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
continue
}
result += word[i]
}
return result
}
// 3. Write a function that takes a string as an argument and returns a string with all
// the vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
func removeVowels(word: String) -> String {
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
continue
}
result += word[i]
}
return result
}
// 4. Write a function that takes a string as an argument and returns a string with all
// the vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
func removeVowels(word: String) -> String {
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
continue
}
result += word[i]
}
return result
}
// 5. Write a function that takes a string as an argument and returns a string with all
// the vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
func removeVowels(word: String) -> String {
var result = ""
for i in 0..<word.count {
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" {
continue
}
result += word[i]
}
return result
}
// 6. Write a function that takes a string
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = word[i] // cannot assign value of type 'Character' to type 'String'
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = word[i] // cannot assign value of type 'Character' to type 'String'
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if word[i] == "a" || word[i] == "e" || word[i] == "i" || word[i] == "o" || word[i] == "u" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result += word[i] // no exact matches in call to subscript
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let chars = Array(word)
for i in 0..<chars.count {
if (vowels.contains(chars[i])) {
return chars[i]
}
}
return ""
}
func firstUniqChar(s: String) -> Int {
let chars = Array(s)
for i in 0..<chars.count {
if (chars.count(chars[i]) == 1) {
return i
}
}
return -1
}
func longestPalindrome(s: String) -> String {
let chars = Array(s)
let palindromes = []
for i in 0..<chars.count {
for j in i..<chars.count {
let substring = chars[i..<j]
if (substring.reversed() == substring) {
palindromes.append(substring)
}
}
}
return palindromes.maxBy(by: { $0.count })!
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let chars = Array(word)
for i in 0..<chars.count {
if (vowels.contains(chars[i])) {
return chars[i]
}
}
return ""
}
// 2.
// Given a string, find the first non-repeating character in it and return it's index.
// If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
func firstUniqChar(s: String) -> Int {
let chars = Array(s)
for i in 0..<chars.count {
if (chars.count(chars[i]) == 1) {
return i
}
}
return -1
}
// 3.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
let chars = Array(s)
let palindromes = []
for i in 0..<chars.count {
for j in i..<chars.count {
let substring = chars[i..<j]
if (substring.reversed() == substring) {
palindromes.append(substring)
}
}
}
return palindromes.maxBy(by: { $0.count })!
}
// 4.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// Example:
// Input: "a"
// Output: "a"
// Input: "ac"
// Output: "a"
func longestPalindrome(s: String) -> String {
let chars = Array(s)
let palindromes = []
for i in 0..<chars.count {
for j in i..<chars.count {
let substring = chars[i..<j]
if (substring.reversed() == substring) {
palindromes.append(substring)
}
}
}
return palindromes.maxBy(by: { $0.count })!
}
// 5.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
// Example:
// Input: "a"
// Output: "a"
// Input: "ac"
// Output: "a"
func longestPalindrome(s: String) -> String {
let chars = Array(s)
let palindromes = []
for i in 0..<chars.count {
for j in i..<chars.count {
let substring = chars[i..<j]
if (substring.reversed() == substring) {
palindromes.append(substring)
}
}
}
return palindromes.maxBy(by: { $0.count })!
}
// 6.
// Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
// Example:
//
if (vowels.contains(chars[i])) { // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
return chars[i] // cannot convert return expression of type 'String.Element' (aka 'Character') to return type 'String'
if (chars.count(chars[i]) == 1) { // cannot call value of non-function type 'Int'
let palindromes = [] // empty collection literal requires an explicit type
if (substring.reversed() == substring) { // binary operator '==' cannot be applied to operands of type '[String.Element]' (aka 'Array<Character>') and 'ArraySlice<String.Element>' (aka 'ArraySlice<Character>')
palindromes.append(substring) // cannot use mutating member on immutable value: 'palindromes' is a 'let' constant
return palindromes.maxBy(by: { $0.count })! // value of type '[Any]' has no member 'maxBy'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let vowelIndexes = []
for i in 0..<word.count {
if vowels.contains(word[i]) {
vowelIndexes.append(i)
}
}
if vowelIndexes.count == 0 {
return ""
}
let closestVowel = ""
for i in 0..<vowelIndexes.count {
if i == 0 {
closestVowel = word[vowelIndexes[i]]
} else {
if abs(vowelIndexes[i] - vowelIndexes[i - 1]) < abs(vowelIndexes[i] - closestVowel) {
closestVowel = word[vowelIndexes[i]]
}
}
}
return closestVowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let vowelIndexes = []
for i in 0..<word.count {
if vowels.contains(word[i]) {
vowelIndexes.append(i)
}
}
if vowelIndexes.count == 0 {
return ""
}
let closestVowel = ""
for i in 0..<vowelIndexes.count {
if i == 0 {
closestVowel = word[vowelIndexes[i]]
} else {
if abs(vowelIndexes[i] - vowelIndexes[i - 1]) < abs(vowelIndexes[i] - closestVowel) {
closestVowel = word[vowelIndexes[i]]
}
}
}
return closestVowel
}
// 2.
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example
// [3, 6, -2, -5, 7, 3]
// The pair (6, 7) has the largest product: 34
// function adjacentElementsProduct(inputArray: [Int]) -> Int {
// var maxProduct = 0
// for i in 0..<inputArray.count - 1 {
// var product = inputArray[i] * inputArray[i + 1]
// if product > maxProduct {
// maxProduct = product
// }
// }
// return maxProduct
// }
// 3.
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example
// [3, 6, -2, -5, 7, 3]
// The pair (6, 7) has the largest product: 34
// function adjacentElementsProduct(inputArray: [Int]) -> Int {
// var maxProduct = 0
// for i in 0..<inputArray.count - 1 {
// var product = inputArray[i] * inputArray[i + 1]
// if product > maxProduct {
// maxProduct = product
// }
// }
// return maxProduct
// }
// 4.
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example
// [3, 6, -2, -5, 7, 3]
// The pair (6, 7) has the largest product: 34
// function adjacentElementsProduct(inputArray: [Int]) -> Int {
// var maxProduct = 0
// for i in 0..<inputArray.count - 1 {
// var product = inputArray[i] * inputArray[i + 1]
// if product > maxProduct {
// maxProduct = product
// }
// }
// return maxProduct
// }
// 5.
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example
// [3, 6, -2, -5, 7, 3]
// The pair (6, 7) has the largest product: 34
// function adjacentElementsProduct(inputArray: [Int]) -> Int {
// var maxProduct = 0
// for i in 0..<inputArray.count - 1 {
// var product = inputArray[i] * inputArray[i + 1]
// if product > maxProduct {
// maxProduct = product
// }
// }
// return maxProduct
// }
// 6.
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example
// [3, 6, -2, -5, 7, 3]
// The pair (6, 7) has the largest product: 34
// function adjacentElementsProduct(inputArray: [Int]) -> Int {
// var maxProduct = 0
// for i in 0..<inputArray.count -
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
func removeSpaces(str: String) -> String {
return str.replace(" ", "")
}
func reverseLetters(str: String) -> String {
return String(str.reversed())
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
// ----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// with all the spaces removed.
// Examples:
// removeSpaces("Hello world") == "Helloworld"
// removeSpaces("Hi") == "Hi"
func removeSpaces(str: String) -> String {
return str.replace(" ", "")
}
// ----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// with all the letters reversed.
// Examples:
// reverseLetters("Hello world") == "dlrow olleH"
// reverseLetters("Hi") == "iH"
func reverseLetters(str: String) -> String {
return String(str.reversed())
}
// ----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string
// with all the letters replaced by their corresponding numbers.
// Examples:
// replaceLetters("Hello world") == "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
stack.pop() // value of type '[String]' has no member 'pop'
return str.replace(" ", "") // missing argument label 'with:' in call
return str.replace(" ", "") // cannot use mutating member on immutable value: 'str' is a 'let' constant
return str.replace(" ", "") // cannot convert return expression of type '()' to return type 'String'
func matchParens(lst: [String]) -> String {
if lst.count == 0 {
return "Yes"
}
var stack = [String]()
for s in lst {
if s == "(" {
stack.append(s)
} else {
if stack.count == 0 {
return "No"
} else {
stack.pop()
}
}
}
if stack.count == 0 {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
if lst.count == 0 {
return "Yes"
}
var stack = [String]()
for s in lst {
if s == "(" {
stack.append(s)
} else {
if stack.count == 0 {
return "No"
} else {
stack.pop()
}
}
}
if stack.count == 0 {
return "Yes"
} else {
return "No"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
stack.pop() // value of type '[String]' has no member 'pop'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
func longestSubstring(s: String) -> Int {
var max = 0
var stack = [String]()
for i in s {
if stack.contains(i) {
while stack.contains(i) {
stack.removeFirst()
}
}
stack.append(i)
max = max(max, stack.count)
}
return max
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
// -----------------------------------------------------------------------------
// 1.10
// Given a string, return the length of the longest substring without
// repeating characters.
// Examples:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var max = 0
var stack = [String]()
for i in s {
if stack.contains(i) {
while stack.contains(i) {
stack.removeFirst()
}
}
stack.append(i)
max = max(max, stack.count)
}
return max
}
// -----------------------------------------------------------------------------
// 1.11
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var max = 0
var stack = [String]()
for i in s {
if stack.contains(i) {
while stack.contains(i) {
stack.removeFirst()
}
}
stack.append(i)
max = max(max, stack.count)
}
return max
}
// -----------------------------------------------------------------------------
// 1.12
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var max = 0
var stack = [String]()
for i in s {
if stack.contains(i) {
while stack.contains(i) {
stack.removeFirst()
}
}
stack.append(i)
max = max(max, stack.count)
}
return max
}
// -----------------------------------------------------------------------------
// 1.13
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var max = 0
var stack = [String]()
for i in s {
if stack.contains(i) {
while stack.contains(i) {
stack.removeFirst()
}
}
stack.append(i)
max = max(max, stack.count)
}
return max
}
// -----------------------------------------------------------------------------
// 1.14
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew"
stack.pop() // value of type '[String]' has no member 'pop'
if stack.contains(i) { // cannot convert value of type 'Character' to expected argument type 'String'
while stack.contains(i) { // cannot convert value of type 'Character' to expected argument type 'String'
stack.append(i) // cannot convert value of type 'Character' to expected argument type 'String'
max = max(max, stack.count) // cannot call value of non-function type 'Int'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for i in lst {
if i == "(" {
stack.append(i)
} else {
if stack.isEmpty {
return "No"
} else {
stack.pop()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------
stack.pop() // value of type '[String]' has no member 'pop'
func matchParens(lst: [String]) -> String {
let open = 0
let close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else {
close += 1
}
if open < close {
return "No"
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
let open = 0
let close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else {
close += 1
}
if open < close {
return "No"
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ---------------------------------------------------------
open += 1 // left side of mutating operator isn't mutable: 'open' is a 'let' constant
close += 1 // left side of mutating operator isn't mutable: 'close' is a 'let' constant
func matchParens(lst: [String]) -> String {
var open = 0
var close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func removeSpaces(s: String) -> String {
return s.trim()
}
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char == char.uppercase {
result += char.lowercase
} else {
result += char.uppercase
}
}
return result
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var open = 0
var close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string
// reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("") == ""
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// with all the spaces removed.
// Examples:
// removeSpaces("hello world") == "helloworld"
// removeSpaces("") == ""
func removeSpaces(s: String) -> String {
return s.trim()
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples:
// removeVowels("hello world") == "hll wrld"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string
// with all the uppercase characters converted to lowercase and all the
// lowercase characters converted to uppercase.
// Examples:
// swapCase("Hello World") == "hELLO wORLD"
// swapCase("") == ""
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char == char.uppercase {
result += char.lowercase
} else {
result += char.uppercase
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples:
// removeVowels("hello world") == "hll wrld"
// removeVowels("") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// with all the uppercase characters converted to lowercase and all the
// lowercase characters converted to uppercase.
// Examples:
// swapCase("Hello World") == "hELLO wORLD"
// swapCase("") == ""
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char == char.uppercase {
result += char.lowercase
} else {
result += char.uppercase
}
}
return result
return s.trim() // value of type 'String' has no member 'trim'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
result += char.lowercase // value of type 'Character' has no member 'lowercase'
result += char.uppercase // value of type 'Character' has no member 'uppercase'
func matchParens(lst: [String]) -> String {
let open = 0
let close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
let open = 0
let close = 0
for char in lst[0] {
if char == "(" {
open += 1
} else if char == ")" {
close += 1
}
}
if open == close {
return "Yes"
} else {
return "No"
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
open += 1 // left side of mutating operator isn't mutable: 'open' is a 'let' constant
close += 1 // left side of mutating operator isn't mutable: 'close' is a 'let' constant
func matchParens(lst: [String]) -> String {
var stack = [String]()
for char in lst {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty() {
return "No"
}
stack.pop()
}
}
return stack.isEmpty() ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for char in lst {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty() {
return "No"
}
stack.pop()
}
}
return stack.isEmpty() ? "Yes" : "No"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[String]' has no member 'pop'
return stack.isEmpty() ? "Yes" : "No" // cannot call value of non-function type 'Bool'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for s in lst {
if s == "(" {
stack.append(s)
} else {
if stack.isEmpty {
return "No"
}
stack.pop()
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for s in lst {
if s == "(" {
stack.append(s)
} else {
if stack.isEmpty {
return "No"
}
stack.pop()
}
}
return stack.isEmpty ? "Yes" : "No"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
stack.pop() // value of type '[String]' has no member 'pop'
func matchParens(lst: [String]) -> String {
var stack = [String]()
for char in lst[0] {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty() {
return "No"
}
stack.pop()
}
}
return stack.isEmpty() ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for char in lst[0] {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty() {
return "No"
}
stack.pop()
}
}
return stack.isEmpty() ? "Yes" : "No"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[String]' has no member 'pop'
return stack.isEmpty() ? "Yes" : "No" // cannot call value of non-function type 'Bool'
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
// 2. Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the minimum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// minimum(arr: [-3, -4, 5], k: 3) == [-3, -4, 5]
// minimum(arr: [4, -4, 4], k: 2) == [-4, -4]
// minimum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [-2]
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}<|endoftext|>// 1. Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
// 2. Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the minimum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// minimum(arr: [-3, -4, 5], k: 3) == [-3, -4, 5]
// minimum(arr: [4, -4, 4], k: 2) == [-4, -4]
// minimum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [-2]
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}<|endoftext|>// 1. Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1
var result = [] // empty collection literal requires an explicit type
result.append(sorted.popLast()) // expression implicitly coerced from 'Int?' to 'Any'
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var sortedArr = arr.sorted()
var result = []
for i in 0..<k {
result.append(sortedArr.popLast())
}
return result
}
func checkIfExist(arr: [Int]) -> Bool {
var result = false
for i in 0..<arr.count {
for j in 0..<arr.count {
if i != j && arr[i] == 2 * arr[j] {
result = true
break
}
}
}
return result
}
func validMountainArray(arr: [Int]) -> Bool {
var result = false
if arr.count >= 3 {
var i = 1
while i < arr.count && arr[i] > arr[i - 1] {
i += 1
}
if i == 1 || i == arr.count {
return false
}
while i < arr.count && arr[i] < arr[i - 1] {
i += 1
}
if i == arr.count {
result = true
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var sortedArr = arr.sorted()
var result = []
for i in 0..<k {
result.append(sortedArr.popLast())
}
return result
}
// 2. Given an array arr of integers, check if there exist two indices i and j such that :
// i != j
// 0 <= i, j < arr.length
// arr[i] == 2 * arr[j]
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. 2 <= arr.length <= 500
// 2. -1000 <= arr[i] <= 1000
// checkIfExist(arr: [2, 3, 1, 5]) == true
// checkIfExist(arr: [2, 4, 3, 5]) == false
// checkIfExist(arr: [2, 4, 3, 5, 5]) == true
func checkIfExist(arr: [Int]) -> Bool {
var result = false
for i in 0..<arr.count {
for j in 0..<arr.count {
if i != j && arr[i] == 2 * arr[j] {
result = true
break
}
}
}
return result
}
// 3. Given an array of integers arr, return true if and only if it is a valid mountain array.
// Recall that arr is a mountain array if and only if:
// 1. arr.length >= 3
// 2. There exists some i with 0 < i < arr.length - 1 such that:
// arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
// arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. 1 <= arr.length <= 104
// 2. 0 <= arr[i] <= 104
// validMountainArray(arr: [0, 3, 2, 1]) == true
// validMountainArray(arr: [0, 2, 3, 4, 5, 2, 1]) == false
// validMountainArray(arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1]) == false
func validMountainArray(arr: [Int]) -> Bool {
var result = false
if arr.count >= 3 {
var i = 1
while i < arr.count && arr[i] > arr[i - 1] {
i += 1
}
if i == 1 || i == arr.count {
return false
}
while i < arr.count && arr[i] < arr[i - 1] {
i += 1
}
if i == arr.count {
result = true
}
}
return result
}
// 4. Given an array of integers arr, return true if and only if it is a valid mountain array.
// Recall that arr is a mountain array if and only if:
// 1. arr.length >= 3
// 2. There exists some i with 0 < i < arr.length - 1 such that:
// arr[0] < arr[1] < ... < arr[i - 1]
// arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. 1 <= arr.length <= 104
// 2. 0 <= arr[i] <= 104
// validMountainArray(arr: [0, 3, 2, 1]) == true
// validMountainArray(arr: [0, 2, 3, 4, 5, 2, 1]) == false
var result = [] // empty collection literal requires an explicit type
result.append(sortedArr.popLast()) // expression implicitly coerced from 'Int?' to 'Any'
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var result = []
var heap = []
for i in 0..<arr.count {
if heap.count < k {
heap.append(arr[i])
} else {
if heap[0] < arr[i] {
heap[0] = arr[i]
}
}
sorted(heap)
}
return heap
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = []
var heap = []
for i in 0..<arr.count {
if heap.count < k {
heap.append(arr[i])
} else {
if heap[0] < arr[i] {
heap[0] = arr[i]
}
}
sorted(heap)
}
return heap
}
// 2. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. 191. 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206.
var result = [] // empty collection literal requires an explicit type
var heap = [] // empty collection literal requires an explicit type
if heap[0] < arr[i] { // cannot convert value of type 'Any' to expected argument type 'Int'
sorted(heap) // cannot find 'sorted' in scope
return heap // cannot convert return expression of type '[Any]' to return type '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap(arr)
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
struct Heap {
var heap: [Int]
init(arr: [Int]) {
self.heap = arr
for i in (arr.count - 1)...0 {
self.heapify(i)
}
}
func pop() -> Int {
if self.heap.count == 0 {
return 0
}
let result = self.heap[0]
self.heap[0] = self.heap.pop()
self.heapify(0)
return result
}
func heapify(i: Int) {
var left = 2 * i + 1
var right = 2 * i + 2
var largest = i
if left < self.heap.count && self.heap[left] > self.heap[largest] {
largest = left
}
if right < self.heap.count && self.heap[right] > self.heap[largest] {
largest = right
}
if largest != i {
self.swap(i, largest)
self.heapify(largest)
}
}
func swap(i: Int, j: Int) {
let temp = self.heap[i]
self.heap[i] = self.heap[j]
self.heap[j] = temp
}
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap(arr)
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
struct Heap {
var heap: [Int]
init(arr: [Int]) {
self.heap = arr
for i in (arr.count - 1)...0 {
self.heapify(i)
}
}
func pop() -> Int {
if self.heap.count == 0 {
return 0
}
let result = self.heap[0]
self.heap[0] = self.heap.pop()
self.heapify(0)
return result
}
func heapify(i: Int) {
var left = 2 * i + 1
var right = 2 * i + 2
var largest = i
if left < self.heap.count && self.heap[left] > self.heap[largest] {
largest = left
}
if right < self.heap.count && self.heap[right] > self.heap[largest] {
largest = right
}
if largest != i {
self.swap(i, largest)
self.heapify(largest)
}
}
func swap(i: Int, j: Int) {
let temp = self.heap[i]
self.heap[i] = self.heap[j]
self.heap[j] = temp
}
}
var arr = [-3, -4, 5]
var k = 3
print(maximum(arr: arr, k: k))
arr = [4, -4, 4]
k = 2
print(maximum(arr: arr, k: k))
arr = [-3, 2, 1, 2, -1, -2, 1]
k = 1
print(maximum(arr: arr, k: k))
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
var heap = Heap(arr) // missing argument label 'arr:' in call
self.heapify(i) // missing argument label 'i:' in call
self.heap[0] = self.heap.pop() // value of type '[Int]' has no member 'pop'
self.heap[0] = self.heap.pop() // cannot assign through subscript: 'self' is immutable
self.heapify(0) // missing argument label 'i:' in call
self.swap(i, largest) // missing argument labels 'i:j:' in call
self.heapify(largest) // missing argument label 'i:' in call
self.heap[i] = self.heap[j] // cannot assign through subscript: 'self' is immutable
self.heap[j] = temp // cannot assign through subscript: 'self' is immutable
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
// 1.1.2
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the minimum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// minimum(arr: [-3, -4, 5], k: 3) == [-3, -4, 5]
// minimum(arr: [4, -4, 4], k: 2) == [-4, -4]
// minimum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [-3]
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}
// 1.1.3
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.popLast())
}
return result
}
// 1.1.4
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the minimum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// minimum(arr: [-3, -4, 5], k: 3) == [-3, -4, 5]
// minimum(arr: [4, -4, 4], k: 2) == [-4, -4]
// minimum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [-3]
func minimum(arr: [Int], k: Int) -> [Int] {
var sorted = arr.sorted()
var result = []
for i in 0..<k {
result.append(sorted.first!)
sorted.remove(at: 0)
}
return result
}
// 1.1.5
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1
var result = [] // empty collection literal requires an explicit type
result.append(sorted.popLast()) // expression implicitly coerced from 'Int?' to 'Any'
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap()
for i in 0..<arr.count {
heap.insert(arr[i])
}
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
struct Heap {
var heap: [Int] = []
var heapSize: Int = 0
init() {
heapSize = 0
}
func insert(val: Int) {
heap.append(val)
heapSize += 1
siftUp(heapSize - 1)
}
func pop() -> Int {
if heapSize == 0 {
return 0
}
var res = heap[0]
heap[0] = heap[heapSize - 1]
heapSize -= 1
siftDown(0)
return res
}
func siftUp(index: Int) {
while index > 0 {
var parent = (index - 1) / 2
if heap[parent] < heap[index] {
heap[parent] = heap[parent] ^ heap[index]
heap[index] = heap[parent] ^ heap[index]
heap[parent] = heap[parent] ^ heap[index]
} else {
break
}
index = parent
}
}
func siftDown(index: Int) {
var left = index * 2 + 1
while left < heapSize {
var right = left + 1
if right < heapSize && heap[right] > heap[left] {
left = right
}
if heap[index] < heap[left] {
heap[index] = heap[index] ^ heap[left]
heap[left] = heap[index] ^ heap[left]
heap[index] = heap[index] ^ heap[left]
} else {
break
}
index = left
left = index * 2 + 1
}
}
}
func smallestK(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap()
for i in 0..<arr.count {
heap.insert(arr[i])
}
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap()
for i in 0..<arr.count {
heap.insert(arr[i])
}
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
struct Heap {
var heap: [Int] = []
var heapSize: Int = 0
init() {
heapSize = 0
}
func insert(val: Int) {
heap.append(val)
heapSize += 1
siftUp(heapSize - 1)
}
func pop() -> Int {
if heapSize == 0 {
return 0
}
var res = heap[0]
heap[0] = heap[heapSize - 1]
heapSize -= 1
siftDown(0)
return res
}
func siftUp(index: Int) {
while index > 0 {
var parent = (index - 1) / 2
if heap[parent] < heap[index] {
heap[parent] = heap[parent] ^ heap[index]
heap[index] = heap[parent] ^ heap[index]
heap[parent] = heap[parent] ^ heap[index]
} else {
break
}
index = parent
}
}
func siftDown(index: Int) {
var left = index * 2 + 1
while left < heapSize {
var right = left + 1
if right < heapSize && heap[right] > heap[left] {
left = right
}
if heap[index] < heap[left] {
heap[index] = heap[index] ^ heap[left]
heap[left] = heap[index] ^ heap[left]
heap[index] = heap[index] ^ heap[left]
} else {
break
}
index = left
left = index * 2 + 1
}
}
}
// 2. 给定一个数组 arr,已知其中所有的值都是非负的,
// 设计一个算法,计算出其中最小的 k 个数。
// 例如,输入4、5、1、6、2、7、3、8这8个数字,
// 则最小的4个数字是1、2、3、4。
// Example 1:
// Input: arr = [1,3,5,7,2,4,6,8], k = 4
// Output: [1,2,3,4]
// Example 2:
// Input: arr = [1,2,3,4,5,6,7,8], k = 4
// Output: [1,2,3,4]
// Example 3:
// Input: arr = [1,2,3,4,5,6,7,8], k = 8
// Output: [1,2,3,4,5,6,7,8]
// Example 4:
// Input: arr = [1,2,3,4,5,6,7,8], k = 4
// Output: [1,2,3,4]
// Note:
// 1. 0 <= k <= arr.length <= 10000
// 2. 0 <= arr[i] <= 10000
func smallestK(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var heap = Heap()
for i in 0..<arr.count {
heap.insert(arr[i])
}
for _ in 0..<k {
result.append(heap.pop())
}
return result
}
// 3. 给定一个数组 arr,已知其中所有的值都是非负的,
// 设计一个算法,计算出其中最小的 k 个数。
// 例如,输入4、5、1、6、2、7、3、8这8个数字,
// 则最小的4个数字是1、2、3、4。
// Example 1:
// Input: arr = [1,3,5
heap.insert(arr[i]) // missing argument label 'val:' in call
heap.append(val) // cannot use mutating member on immutable value: 'self' is immutable
heapSize += 1 // left side of mutating operator isn't mutable: 'self' is immutable
siftUp(heapSize - 1) // missing argument label 'index:' in call
heap[0] = heap[heapSize - 1] // cannot assign through subscript: 'self' is immutable
heapSize -= 1 // left side of mutating operator isn't mutable: 'self' is immutable
siftDown(0) // missing argument label 'index:' in call
heap[parent] = heap[parent] ^ heap[index] // cannot assign through subscript: 'self' is immutable
heap[index] = heap[parent] ^ heap[index] // cannot assign through subscript: 'self' is immutable
heap[parent] = heap[parent] ^ heap[index] // cannot assign through subscript: 'self' is immutable
index = parent // cannot assign to value: 'index' is a 'let' constant
heap[index] = heap[index] ^ heap[left] // cannot assign through subscript: 'self' is immutable
heap[left] = heap[index] ^ heap[left] // cannot assign through subscript: 'self' is immutable
heap[index] = heap[index] ^ heap[left] // cannot assign through subscript: 'self' is immutable
index = left // cannot assign to value: 'index' is a 'let' constant
heap.insert(arr[i]) // missing argument label 'val:' in call
func maximum(arr: [Int], k: Int) -> [Int] {
// TODO: implement
return []
}
public func test_maximum() {
print("maximum ...")
print("Example 1: ", get(try solution().maximum(arr: [-3, -4, 5], k: 3)))
print("Example 2: ", get(try solution().maximum(arr: [4, -4, 4], k: 2)))
print("Example 3: ", get(try solution().maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1)))
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
// TODO: implement
return []
}
public func test_maximum() {
print("maximum ...")
print("Example 1: ", get(try solution().maximum(arr: [-3, -4, 5], k: 3)))
print("Example 2: ", get(try solution().maximum(arr: [4, -4, 4], k: 2)))
print("Example 3: ", get(try solution().maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1)))
}
/*
*
* 2. Given an array arr of integers and a positive integer k, return a sorted array
* of length k with the maximum k numbers in arr.
*
* Example 1:
*
* Input: arr = [-3,-4,5], k = 3
* Output: [-4,-3,5]
*
* Example 2:
*
* Input: arr = [4,-4,4], k = 2
* Output: [4,4]
*
* Example 3:
*
* Input: arr = [-3,2,1,2,-1,-2,1], k = 1
* Output: [2]
*
*
* Constraints:
*
* 1. The length of the array will be in the range of [1, 1000].
* 2. The elements in the array will be in the range of [-1000, 1000].
* 3. 0 <= k <= len(arr)
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
print("Example 1: ", get(try solution().maximum(arr: [-3, -4, 5], k: 3))) // cannot find 'get' in scope
print("Example 1: ", get(try solution().maximum(arr: [-3, -4, 5], k: 3))) // cannot find 'solution' in scope
print("Example 2: ", get(try solution().maximum(arr: [4, -4, 4], k: 2))) // cannot find 'solution' in scope
print("Example 2: ", get(try solution().maximum(arr: [4, -4, 4], k: 2))) // cannot find 'get' in scope
print("Example 3: ", get(try solution().maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1))) // cannot find 'get' in scope
print("Example 3: ", get(try solution().maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1))) // cannot find 'solution' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
// TODO: your code goes here
return []
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
// TODO: your code goes here
return []
}
let arr = [-3, -4, 5]
let k = 3
print(maximum(arr: arr, k: k))
let arr2 = [4, -4, 4]
let k2 = 2
print(maximum(arr: arr2, k: k2))
let arr3 = [-3, 2, 1, 2, -1, -2, 1]
let k3 = 1
print(maximum(arr: arr3, k: k3))
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
// 1. 排序
// 2. 取前k个
// 3. 返回
return []
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
// 1. 排序
// 2. 取前k个
// 3. 返回
return []
}
let arr = [-3, -4, 5]
let k = 3
print(maximum(arr: arr, k: k))
let arr2 = [4, -4, 4]
let k2 = 2
print(maximum(arr: arr2, k: k2))
let arr3 = [-3, 2, 1, 2, -1, -2, 1]
let k3 = 1
print(maximum(arr: arr3, k: k3))
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------
// XCTAssertTrue failed
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
// 1. 排序
// 2. 取前k个
// 3. 排序
// 4. 取前k个
// 5. 排序
// 6. 取前k个
// 7. 排序
// 8. 取前k个
// 9. 排序
// 10. 取前k个
// 11. 排序
// 12. 取前k个
// 13. 排序
// 14. 取前k个
// 15. 排序
// 16. 取前k个
// 17. 排序
// 18. 取前k个
// 19. 排序
// 20. 取前k个
// 21. 排序
// 22. 取前k个
// 23. 排序
// 24. 取前k个
// 25. 排序
// 26. 取前k个
// 27. 排序
// 28. 取前k个
// 29. 排序
// 30. 取前k个
// 31. 排序
// 32. 取前k个
// 33. 排序
// 34. 取前k个
// 35. 排序
// 36. 取前k个
// 37. 排序
// 38. 取前k个
// 39. 排序
// 40. 取前k个
// 41. 排序
// 42. 取前k个
// 43. 排序
// 44. 取前k个
// 45. 排序
// 46. 取前k个
// 47. 排序
// 48. 取前k个
// 49. 排序
// 50. 取前k个
// 51. 排序
// 52. 取前k个
// 53. 排序
// 54. 取前k个
// 55. 排序
// 56. 取前k个
// 57. 排序
// 58. 取前k个
// 59. 排序
// 60. 取前k个
// 61. 排序
// 62. 取前k个
// 63. 排序
// 64. 取前k个
// 65. 排序
// 66. 取前k个
// 67. 排序
// 68. 取前k个
// 69. 排序
// 70. 取前k个
// 71. 排序
// 72. 取前k个
// 73. 排序
// 74. 取前k个
// 75. 排序
// 76. 取前k个
// 77. 排序
// 78. 取前k个
// 79. 排序
// 80. 取前k个
// 81. 排序
// 82. 取前k个
// 83. 排序
// 84. 取前k个
// 85. 排序
// 86. 取前k个
// 87. 排序
// 88. 取前k个
// 89. 排序
// 90. 取前k个
// 91. 排序
// 92. 取前k个
// 93. 排序
// 94. 取前k个
// 95. 排序
// 96. 取前k个
// 97. 排序
// 98. 取前k个
//
XCTAssertTrue(maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [4, -4, 4], k: 2) == [4, 4]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [123, -123, 20, 0, 1, 2, -3], k: 3) == [2, 20, 123]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [-123, 20, 0, 1, 2, -3], k: 4) == [0, 1, 2, 20]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [5, 15, 0, 3, -13, -8, 0], k: 7) == [-13, -8, 0, 0, 3, 5, 15]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [-1, 0, 2, 5, 3, -10], k: 2) == [3, 5]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [1, 0, 5, -7], k: 1) == [5]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [4, -4], k: 2) == [-4, 4]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [-10, 10], k: 2) == [-10, 10]) // cannot find 'maximum' in scope
XCTAssertTrue(maximum(arr: [1, 2, 3, -23, 243, -400, 0], k: 0) == [] as [Int]) // cannot find 'maximum' in scope
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
if lst[i] % 2 != 0 {
sum += lst[i]
}
}
}
return sum
}
func solution(s: String) -> String {
var stringArray = s.split(" ")
var newString = ""
for i in 0..<stringArray.count {
if i == 0 {
newString += stringArray[i].capitalized
} else {
newString += stringArray[i].capitalized
}
if i != stringArray.count - 1 {
newString += " "
}
}
return newString.reverse()
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
if lst[i] % 2 != 0 {
sum += lst[i]
}
}
}
return sum
}
// 2.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " input example "
// " Example Input Example " ==> " iNPUT eXAMPLE INPUT eXAMPLE "
func solution(s: String) -> String {
var stringArray = s.split(" ")
var newString = ""
for i in 0..<stringArray.count {
if i == 0 {
newString += stringArray[i].capitalized
} else {
newString += stringArray[i].capitalized
}
if i != stringArray.count - 1 {
newString += " "
}
}
return newString.reverse()
}
// 3.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " input example "
// " Example Input Example " ==> " iNPUT eXAMPLE INPUT eXAMPLE "
func solution(s: String) -> String {
var stringArray = s.split(" ")
var newString = ""
for i in 0..<stringArray.count {
if i == 0 {
newString += stringArray[i].capitalized
} else {
newString += stringArray[i].capitalized
}
if i != stringArray.count - 1 {
newString += " "
}
}
return newString.reverse()
}
// 4.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " input example "
// " Example Input Example " ==> " iNPUT eXAMPLE INPUT eXAMPLE "
func solution(s: String) -> String {
var stringArray = s.split(" ")
var newString = ""
for i in 0..<stringArray.count {
if i == 0 {
newString += stringArray[i].capitalized
} else {
newString += stringArray[i].capitalized
}
if i != stringArray.count - 1 {
newString += " "
}
}
return newString.reverse()
}
// 5.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// " Example Input " ==> " input example "
// " Example Input Example " ==> " iNPUT eXAMPLE INPUT eXAMPLE
var stringArray = s.split(" ") // no exact matches in call to instance method 'split'
return newString.reverse() // value of type 'String' has no member 'reverse'
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 != 0 {
sum += lst[i]
}
}
return sum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 && i % 2 == 1 {
sum += lst[i]
}
}
return sum
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 2. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 3. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 4. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 5. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 6. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 7. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr:
func addElements(arr: [Int], k: Int) -> Int { // invalid redeclaration of 'addElements(arr:k:)'
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
// 2. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 3. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 4. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 5. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 6. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 7. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
//
func addElements(arr: [Int], k: Int) -> Int { // invalid redeclaration of 'addElements(arr:k:)'
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
func reverseString(s: String) -> String {
var reversed = ""
for i in (s.length-1)..<0 {
reversed += s[i]
}
return reversed
}
func firstUniqChar(s: String) -> Int {
var chars = [Int](repeating: 0, count: 26)
for c in s {
chars[c - 'a'] += 1
}
for i in 0..<s.length {
if chars[s[i] - 'a'] == 1 {
return i
}
}
return -1
}
func numSubarraysWithSum(nums: [Int], k: Int) -> Int {
var count = 0
var sum = 0
var left = 0
for right in 0..<nums.count {
sum += nums[right]
while left <= right && sum > k {
sum -= nums[left]
left += 1
}
if sum == k {
count += 1
}
}
return count
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 12. Write a function that takes a string as input and returns the string reversed.
// Example:
// Constraints:
// 1. 0 <= len(s) <= 10000
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
var reversed = ""
for i in (s.length-1)..<0 {
reversed += s[i]
}
return reversed
}
// 13. Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
// Example:
// Constraints:
// 1. 0 <= len(s) <= 105
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var chars = [Int](repeating: 0, count: 26)
for c in s {
chars[c - 'a'] += 1
}
for i in 0..<s.length {
if chars[s[i] - 'a'] == 1 {
return i
}
}
return -1
}
// 14. Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
// Example:
// Constraints:
// 1. 0 <= len(s) <= 105
// firstUniqChar("leetcode") == 0
// firstUniqChar("loveleetcode") == 2
func firstUniqChar(s: String) -> Int {
var chars = [Int](repeating: 0, count: 26)
for c in s {
chars[c - 'a'] += 1
}
for i in 0..<s.length {
if chars[s[i] - 'a'] == 1 {
return i
}
}
return -1
}
// 15. Given an integer array nums, return the number of subarrays filled with 0.
// Example:
// Constraints:
// 1. 1 <= nums.length <= 2 * 104
// 2. 0 <= nums[i] <= 1
// numSubarraysWithSum(nums: [0, 1, 0, 1], k: 1) == 4
func numSubarraysWithSum(nums: [Int], k: Int) -> Int {
var count = 0
var sum = 0
var left = 0
for right in 0..<nums.count {
sum += nums[right]
while left <= right && sum > k {
sum -= nums[left]
left += 1
}
if sum == k {
count += 1
}
}
return count
}
// 16. Given an integer array nums, return the number of subarrays filled with 0.
// Example:
// Constraints:
// 1. 1 <= nums.length <= 2 * 104
// 2. 0 <= nums[i] <= 1
// numSubarraysWithSum(nums: [0, 1, 0, 1], k: 1) == 4
func numSubarraysWithSum(nums: [Int], k: Int) -> Int {
var count = 0
var sum = 0
var left = 0
for right in 0..<nums.count {
sum += nums[right]
while left <= right && sum > k {
sum -= nums[left]
left += 1
}
if sum == k {
count +=
for i in (s.length-1)..<0 { // value of type 'String' has no member 'length'
chars[c - 'a'] += 1 // binary operator '-' cannot be applied to two 'Character' operands
chars[c - 'a'] += 1 // single-quoted string literal found, use '"'
for i in 0..<s.length { // value of type 'String' has no member 'length'
if chars[s[i] - 'a'] == 1 { // single-quoted string literal found, use '"'
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
func sumOfArrayExceptMaxAndMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
var sum = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
for i in 0..<arr.count {
if arr[i] != max && arr[i] != min {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 2. Given an array of integers arr, return the sum of all the elements of
// the array, except the maximum and minimum elements of the array.
// If there are multiple elements with the same value,
// include all such values.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5]) == 3
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5]) == 9
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5, 5]) == 14
func sumOfArrayExceptMaxAndMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
var sum = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
for i in 0..<arr.count {
if arr[i] != max && arr[i] != min {
sum += arr[i]
}
}
return sum
}
// 3. Given an array of integers arr, return the sum of all the elements of
// the array, except the maximum and minimum elements of the array.
// If there are multiple elements with the same value,
// include all such values.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5]) == 3
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5]) == 9
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5, 5]) == 14
func sumOfArrayExceptMaxAndMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
var sum = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
for i in 0..<arr.count {
if arr[i] != max && arr[i] != min {
sum += arr[i]
}
}
return sum
}
// 4. Given an array of integers arr, return the sum of all the elements of
// the array, except the maximum and minimum elements of the array.
// If there are multiple elements with the same value,
// include all such values.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5]) == 3
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5]) == 9
// sumOfArrayExceptMaxAndMin(arr: [1, 2, 3, 4, 5, 5, 5]) == 14
func sumOfArrayExceptMaxAndMin(arr: [Int]) -> Int {
var max = arr[0]
var min = arr[0]
var sum = 0
for i in 0.
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 2. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 3. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 4. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 5. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 6. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += arr[i]
}
return sum
}
// 7. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
func addElements(arr: [Int], k: Int) -> Int { // invalid redeclaration of 'addElements(arr:k:)'
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
func removeSmallestAndLargest(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
var sum = 0
for i in 0..<arr.count {
if arr[i] != min && arr[i] != max {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
// 2. Given an array of integers arr, return the sum of all the elements of arr after
// removing the smallest and largest elements from arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// removeSmallestAndLargest(arr: [1, 2, 3, 4, 5]) == 10
func removeSmallestAndLargest(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
var sum = 0
for i in 0..<arr.count {
if arr[i] != min && arr[i] != max {
sum += arr[i]
}
}
return sum
}
// 3. Given an array of integers arr, return the sum of all the elements of arr after
// removing the smallest and largest elements from arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// removeSmallestAndLargest(arr: [1, 2, 3, 4, 5]) == 10
func removeSmallestAndLargest(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
var sum = 0
for i in 0..<arr.count {
if arr[i] != min && arr[i] != max {
sum += arr[i]
}
}
return sum
}
// 4. Given an array of integers arr, return the sum of all the elements of arr after
// removing the smallest and largest elements from arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// removeSmallestAndLargest(arr: [1, 2, 3, 4, 5]) == 10
func removeSmallestAndLargest(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
var sum = 0
for i in 0..<arr.count {
if arr[i] != min && arr[i] != max {
sum += arr[i]
}
}
return sum
}
// 5. Given an array of integers arr, return the sum of all the elements of arr after
// removing the smallest and largest elements from arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// removeSmallestAndLargest(arr: [1, 2, 3, 4, 5]) == 10
func removeSmallestAndLargest(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
func sumEvenNumbers(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 {
sum += arr[i]
}
}
return sum
}
func sumGreaterThan5(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 5 {
sum += arr[i]
}
}
return sum
}
func sumLessThan5(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] < 5 {
sum += arr[i]
}
}
return sum
}
func sumBetween5And10(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 5 && arr[i] < 10 {
sum += arr[i]
}
}
return sum
}
func sumNotBetween5And10(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] < 5 || arr[i] > 10 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 100 {
sum += arr[i]
}
}
return sum
}
// 1.2. Write a function that takes an array of integers and returns the sum of all the even numbers in the array.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumEvenNumbers([1, 2, 3, 4, 5, 6]) == 12
func sumEvenNumbers(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] % 2 == 0 {
sum += arr[i]
}
}
return sum
}
// 1.3. Write a function that takes an array of integers and returns the sum of all the numbers in the array that are greater than 5.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumGreaterThan5([6, 7, 8, 9, 10, 11]) == 30
func sumGreaterThan5(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 5 {
sum += arr[i]
}
}
return sum
}
// 1.4. Write a function that takes an array of integers and returns the sum of all the numbers in the array that are less than 5.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumLessThan5([4, 5, 6, 7, 8, 9]) == 20
func sumLessThan5(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] < 5 {
sum += arr[i]
}
}
return sum
}
// 1.5. Write a function that takes an array of integers and returns the sum of all the numbers in the array that are between 5 and 10 (inclusive).
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumBetween5And10([5, 6, 7, 8, 9, 10]) == 30
func sumBetween5And10(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 5 && arr[i] < 10 {
sum += arr[i]
}
}
return sum
}
// 1.6. Write a function that takes an array of integers and returns the sum of all the numbers in the array that are not between 5 and 10 (inclusive).
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= arr[i] <= 100
// sumNotBetween5And10([5, 7, 8, 10, 11]) == 20
func sumNotBetween5And10(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] < 5 || arr[i] > 10 {
sum += arr[i]
}
}
return sum
}
// 1.7. Write a function that takes an array of integers and returns the sum of all the numbers in the array that are not between 5 and 10 (inclusive) and are odd.
// Example:
// Constraints
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 2. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 3. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 4. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 5. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 1000 {
sum += arr[i]
}
}
return sum
}
// 6. Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most k digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 2. Given an array of integers, return the sum of all the positive integers in the array.
// For example:
// sum_positive([1,2,3,4,5]) returns 15
// sumPositive([1,-2,3,-4,5]) returns 12
// sumPositive([]) returns 0
// sumPositive([-1,2,-3,4,-5]) returns 6
// sumPositive([-1,2,-3,-4,5]) returns 12
// sumPositive([-1,2,3,-4,5,-6]) returns 15
// sumPositive([1,2,3,4,5,-6]) returns 15
// sumPositive([1,2,3,4,5,6]) returns 21
// sumPositive([1,2,3,4,5,6,-7]) returns 30
// sumPositive([1,2,3,4,5,6,-7,-8]) returns 40
// sumPosimple([1,2,3,4,5,6,-7,-8,-9]) returns 45
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10]) returns 55
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11]) returns 66
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12]) returns 78
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13]) returns 90
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14]) returns 104
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15]) returns 120
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16]) returns 136
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17]) returns 152
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18]) returns 168
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19]) returns 184
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-20]) returns 200
// sumPositive([1,2,3,4,5,6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
func sum_of_first_odd_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2 * 2
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 2. Given a positive integer n, return the sum of the first n even numbers.
// For example:
// sum_of_first_even_numbers(5) returns 10 # 2 + 4 + 6 + 8 + 10 = 10
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// 3. Given a positive integer n, return the sum of the first n odd numbers.
// For example:
// sum_of_first_odd_numbers(5) returns 9 # 1 + 3 + 5 + 7 + 9 = 9
func sum_of_first_odd_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2 * 2
}
// 4. Given a positive integer n, return the sum of the first n even numbers.
// For example:
// sum_of_first_even_numbers(5) returns 10 # 2 + 4 + 6 + 8 + 10 = 10
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// 5. Given a positive integer n, return the sum of the first n odd numbers.
// For example:
// sum_of_first_odd_numbers(5) returns 9 # 1 + 3 + 5 + 7 + 9 = 9
func sum_of_first_odd_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2 * 2
}
// 6. Given a positive integer n, return the sum of the first n even numbers.
// For example:
// sum_of_first_even_numbers(5) returns 10 # 2 + 4 + 6 + 8 + 10 = 10
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// 7. Given a positive integer n, return the sum of the first n odd numbers.
// For example:
// sum_of_first_odd_numbers(5) returns 9 # 1 + 3 + 5 + 7 + 9 = 9
func sum_of_first_odd_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2 * 2
}
// 8. Given a positive integer n, return the sum of the first n even numbers.
// For example:
// sum_of_first_even_numbers(5) returns 10 # 2 + 4 + 6 + 8 + 10 = 10
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// 9. Given a positive integer n, return the sum of the first n odd numbers.
// For example:
// sum_of_first_odd_numbers(5) returns 9 # 1 + 3 + 5 + 7 + 9 = 9
func sum_of_first_odd_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2 * 2
}
// 10. Given a positive integer n, return the sum of the first n even numbers.
// For example:
// sum_of_first_even_numbers(5) returns 10 # 2 + 4 + 6 + 8 + 10 = 10
func sum_of_first_even_numbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// 11. Given a positive integer n, return the sum of the first n odd numbers.
// For example:
// sum_of_first
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
result.append(i)
}
return result
}
func getOddCollatz(n: Int) -> Int {
var result = 0
var i = 1
while i <= n {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
result += i
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
result.append(i)
}
return result
}
// 2. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note: 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> Int {
var result = 0
var i = 1
while i <= n {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
result += i
}
return result
}
// 3. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note: 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> Int {
var result = 0
var i = 1
while i <= n {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
result += i
}
return result
}
// 4. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note: 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
collatz.append(i)
}
return collatz
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
collatz.append(i)
}
return collatz
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note: 1. Collatz(1) is [1]. 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
collatz.append(i)
}
return collatz
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note: 1. Collatz(1) is [1]. 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var i = n
while i > 1 {
if i % 2 == 0 {
i /= 2
} else {
i = 3 * i + 1
}
collatz.append(i)
}
return collatz
}
// ----------------------------------------------------------------------------------------------------------------------
// 1. Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
func getEvenCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
if current % 2 == 0 {
result.append(current)
}
}
return result
}
func getOddEvenCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 2. Given a positive integer n, return a sorted array that has the even numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_even_collatz(5) returns [2, 4] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the even numbers are only 2, and 4.
// getEvenCollatz(n: 5) == [2, 4]
func getEvenCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
if current % 2 == 0 {
result.append(current)
}
}
return result
}
// 3. Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence and the even numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_even_collatz(5) returns [1, 5, 2, 4] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddEvenCollatz(n: 5) == [1, 5, 2, 4]
func getOddEvenCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 4. Given a positive integer n, return a sorted array that has the even numbers in collatz sequence and the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_even_odd_collatz(5) returns [2, 4, 1, 3] # The collatz sequence for 5 is [5, 16,
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 3 != 0 && i % 5 != 0 && i % 7 != 0 {
result += i
}
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 2. Given a positive integer n, return the sum of all integers in the range [1, n] that are not a multiple of 3, 5, or 7.
// For example:
// sum_not_multiple(10) returns 20 # 1 + 2 + 4 + 7 + 8 + 11 + 13 + 14 + 16 + 18 = 20
// sumNotMultiple(n: 10) == 20
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 3 != 0 && i % 5 != 0 && i % 7 != 0 {
result += i
}
}
return result
}
// 3. Given a positive integer n, return the sum of all integers in the range [1, n] that are not a multiple of 3, 5, or 7.
// For example:
// sum_not_multiple(10) returns 20 # 1 + 2 + 4 + 7 + 8 + 11 + 13 + 14 + 16 + 18 = 20
// sumNotMultiple(n: 10) == 20
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 3 != 0 && i % 5 != 0 && i % 7 != 0 {
result += i
}
}
return result
}
// 4. Given a positive integer n, return the sum of all integers in the range [1, n] that are not a multiple of 3, 5, or 7.
// For example:
// sum_not_multiple(10) returns 20 # 1 + 2 + 4 + 7 + 8 + 11 + 13 + 14 + 16 + 18 = 20
// sumNotMultiple(n: 10) == 20
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 3 != 0 && i % 5 != 0 && i % 7 != 0 {
result += i
}
}
return result
}
// 5. Given a positive integer n, return the sum of all integers in the range [1, n] that are not a multiple of 3, 5, or 7.
// For example:
// sum_not_multiple(10) returns 20 # 1 + 2 + 4 + 7 + 8 + 11 + 13 + 14 + 16 + 18 = 20
// sumNotMultiple(n: 10) == 20
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 3 != 0 && i % 5 != 0 && i % 7 != 0 {
result += i
}
}
return result
}
// 6. Given a positive integer n, return the sum of all integers in the range [1, n] that are not a multiple of 3, 5, or 7.
// For example:
// sum_not_multiple(10) returns 20 # 1 + 2 + 4 + 7 + 8 + 11 + 13 + 14 + 16 + 18 = 20
// sumNotMultiple(n: 10) == 20
func sumNotMultiple(n: Int) -> Int {
var result = 0
for i in 1...n {
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
func getOddCollatz(n: Int) -> Int {
var result = 0
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result += current
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// 2. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> Int {
var result = 0
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result += current
}
return result
}
// 3. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> Int {
var result = 0
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result += current
}
return result
}
// 4. Given a positive integer n, return the sum of all integers in the range [1, n] that are not in the Collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current > 1 {
if current % 2 == 0 {
current /= 2
} else {
current = 3 * current + 1
}
result.append(current)
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
result.append(current)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var current = n
while current != 1 {
if current % 2 == 0 {
current /= 2
} else {
current = current * 3 + 1
}
result.append(current)
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countBits(number: Int) -> Int {
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 3. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count
}
// 4. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count
}
// 5. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count
}
// 6. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count
}
// 7. Write a function that takes an integer as
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count // type 'Character' has no member 'oneline'
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count // cannot call value of non-function type 'Int'
return String(number, radix: 2).count(for: Character.oneline).filter(Character.oneline.isOne).count // type 'Character' has no member 'oneline'
func validDate(date: String) -> Bool {
let components = date.split(separator: "-").map { Int($0) }
if components.count != 3 {
return false
}
let month = components[0]
let day = components[1]
let year = components[2]
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
import Foundation
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let components = date.split(separator: "-").map { Int($0) }
if components.count != 3 {
return false
}
let month = components[0]
let day = components[1]
let year = components[2]
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
var result = validDate(date: "03-11-2000")
print(result)
result = validDate(date: "15-01-2012")
print(result)
result = validDate(date: "04-0-2040")
print(result)
result = validDate(date: "06-04-2020")
print(result)
result = validDate(date: "06/04/2020")
print(result)<|endoftext|>//
// main.swift
// Swift-101
//
// Created by 임성민 on 2021/04/17.
//
import Foundation
// 1. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 2. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 3. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 4. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 5. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 6. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b = 20
var c = 30
var result = a + b + c
print(result)
// 7. 아래 코드를 실행하면 어떤 값이 출력될까?
var a = 10
var b =
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let year = Int(dateArray[2])! // initialization of immutable value 'year' was never used; consider replacing with assignment to '_' or removing it
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let day = Int(dateArray[1])
let month = Int(dateArray[0])
let year = Int(dateArray[2])
if day < 1 || day > 31 {
return false
}
if month < 1 || month > 12 {
return false
}
if month == 2 {
if year % 4 == 0 {
if day > 29 {
return false
}
} else {
if day > 28 {
return false
}
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let day = Int(dateArray[1])
let month = Int(dateArray[0])
let year = Int(dateArray[2])
if day < 1 || day > 31 {
return false
}
if month < 1 || month > 12 {
return false
}
if month == 2 {
if year % 4 == 0 {
if day > 29 {
return false
}
} else {
if day > 28 {
return false
}
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day > 30 {
return false
}
}
return true
}
var validDate = validDate(date: "03-11-2000")
print(validDate)
var validDate = validDate(date: "15-01-2012")
print(validDate)
var validDate = validDate(date: "04-0-2040")
print(validDate)
var validDate = validDate(date: "06-04-2020")
print(validDate)<|endoftext|>// 1. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first character removed.
// 2. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last character removed.
// 3. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last characters removed.
// 4. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first three characters removed.
// 5. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last three characters removed.
// 6. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last three characters removed.
// 7. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first four characters removed.
// 8. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last four characters removed.
// 9. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last four characters removed.
// 10. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first five characters removed.
// 11. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last five characters removed.
// 12. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last five characters removed.
// 13. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first six characters removed.
// 14. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last six characters removed.
// 15. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last six characters removed.
// 16. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first seven characters removed.
// 17. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the last seven characters removed.
// 18. Write a function that takes a string as an argument and returns a new string that contains the value of the original string with the first and last seven characters removed.
// 19. Write a function that takes a string as an argument and returns a new string that contains the value of the original string
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if year % 4 == 0 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day > 28 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-").map { $0.trim() }
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countBits(number: Int) -> Int {
return String(number).count(for: Character.one)
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-").map { $0.trim() }
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 11. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number).count(for: Character.one)
}
// 12. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number).count(for: Character.one)
}
// 13. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number).count(for: Character.one)
}
// 14. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
return String(number).count(for: Character.one)
}
// 15. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(12
let dateArray = date.split(separator: "-").map { $0.trim() } // reference to member 'trim' cannot be resolved without a contextual type
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return String(number).count(for: Character.one) // type 'Character' has no member 'one'
return String(number).count(for: Character.one) // cannot call value of non-function type 'Int'
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
if number % 2 == 1 {
count += 1
}
number /= 2
}
return count
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 3. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
if number % 2 == 1 {
count += 1
}
number /= 2
}
return count
}
// 4. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 5. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
if number % 2 == 1 {
count += 1
}
number /= 2
}
return count
}
// 6. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
if number % 2 == 1 {
count += 1
}
number /= 2
}
return count
}
// 7. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
number /= 2 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
func seven(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 10 == 7 {
count += 1
}
n = n / 10
}
return count
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 10. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 11. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 2 == 1 {
count += 1
}
n = n / 2
}
return count
}
// 12. Write a function that takes a number as input, and returns the number of times 7 appears as a digit of that number.
// Example: The number 12877 has 4 7s.
// seven(12877) == 4
// seven(123456789) == 0
// seven(74186234) == 5
// seven(77777777) == 7
// seven(9999999999999) == 9
func seven(n: Int) -> Int {
var count = 0
while n > 0 {
if n % 10 == 7 {
count += 1
}
n = n / 10
}
return count
}
// 13. Write a function that takes a number as input, and returns the sum of the digits that make up the number.
// Example: The sum of the digits of 123 is 6.
// sumDigits(123) == 6
// sumDigits(498123) == 26
// sumDigits(4981234) == 26
// sumDigits(49812345) == 26
// sumDigits(498123456) == 26
// sumDigits(4981234567) == 26
// sumDigits(49812345678) == 26
// sumDigits(498123456789) == 26
// sumDigits(4981234567890) == 26
// sumDigits(49812345678901) == 26
// sumDigits(498123456789012) == 26
// sumDigits(4981234567890123) == 26
// sumDigits(49812345678901234)
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
n = n / 2 // cannot assign to value: 'n' is a 'let' constant
n = n / 10 // cannot assign to value: 'n' is a 'let' constant
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(input: String) -> String {
return String(input.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 11. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(input: String) -> String {
return String(input.reversed())
}
// 12. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 13. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(input: String) -> String {
return String(input.reversed())
}
// 14. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 15. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 16. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
func countBits(n: Int) -> Int {
var count = 0
while n != 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// 2. Write a function that takes a string as input and returns the string reversed.
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// 3. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
// countBits(1234) == 5
// countBits(4) == 1
// countBits(7) == 3
// countBits(9) == 2
// countBits(10) == 2
func countBits(n: Int) -> Int {
var count = 0
while n > 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 4. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number,
// even if the number is negative.
// For example, the binary representation of -23 is -10111, so the function should return 2, because only two bits are equal to one.
// Note: The input will be a 32-bit integer.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
// countBits(1234) == 5
// countBits(23) == 2
// countBits(10) == 2
// countBits(-3) == 2
func countBits(n: Int) -> Int {
var count = 0
while n != 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 5. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number,
// even if the number is negative.
// For example, the binary representation of -23 is -10111, so the function should return 2, because only two bits are equal to one.
// Note: The input will be a 32-bit integer.
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
// countBits(1234) == 5
// countBits(23) == 2
// countBits(10) == 2
// countBits(-3) == 2
func countBits(n: Int) -> Int {
var count = 0
while n != 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
// 6. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number,
let year = Int(dateArray[2])! // initialization of immutable value 'year' was never used; consider replacing with assignment to '_' or removing it
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func countBits(n: Int) -> Int { // invalid redeclaration of 'countBits(n:)'
n >>= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
func removeSpaces(str: String) -> String {
return str.trim()
}
func swapCase(str: String) -> String {
return str.uppercaseString.lowercaseString
}
func removeVowels(str: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in str {
if !vowels.contains(char) {
result += char
}
}
return result
}
func removeDuplicates(str: String) -> String {
var result = ""
for char in str {
if !result.contains(char) {
result += char
}
}
return result
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])
let day = Int(dateArray[1])
let year = Int(dateArray[2])
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// with all the spaces removed.
// removeSpaces(str: "Hello World") == "HelloWorld"
// removeSpaces(str: " Hello World ") == "HelloWorld"
// removeSpaces(str: "") == ""
func removeSpaces(str: String) -> String {
return str.trim()
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the uppercase characters converted to lowercase and all the
// lowercase characters converted to uppercase.
// swapCase(str: "Hello World") == "hELLO wORLD"
// swapCase(str: " Hello World ") == " hELLO wORLD "
// swapCase(str: "") == ""
func swapCase(str: String) -> String {
return str.uppercaseString.lowercaseString
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// removeVowels(str: "Hello World") == "Hll Wrld"
// removeVowels(str: " Hello World ") == " Hll Wrld "
// removeVowels(str: "") == ""
func removeVowels(str: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in str {
if !vowels.contains(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// with all the repeated characters removed.
// removeDuplicates(str: "Hello World") == "Heo Wrd"
// removeDuplicates(str: " Hello World ") == " Heo Wrd "
// removeDuplicates(str: "") == ""
func removeDuplicates(str: String) -> String {
var result = ""
for char in str {
if !result.contains(char) {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// with all the repeated characters removed, while maintaining the order of
// the remaining characters.
// removeDuplicatesKeepOrder(str: "Hello World") == "Hello World"
// removeDuplicatesKeepOrder(str: " Hello World ") == " Hello World "
// removeDuplicatesKeepOrder(str: "") == ""
func removeDuplicatesKeepOrder(str: String) -> String {
var result = ""
for char
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if month < 1 || month > 12 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 29 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 30 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if day < 1 || day > 31 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return str.trim() // value of type 'String' has no member 'trim'
return str.uppercaseString.lowercaseString // value of type 'String' has no member 'uppercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!
let letters = txt.count(for: .letter) // cannot call value of non-function type 'Int'
let letters = txt.count(for: .letter) // cannot infer contextual base in reference to member 'letter'
return .success(words) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.isEmpty {
return .failure(0)
}
let count = words.count
let odd = 0
for word in words {
let letters = word.map {
let letter = String($0)
if letter.isLower {
odd += 1
}
}
}
return .success(count == odd ? count : odd)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.isEmpty {
return .failure(0)
}
let count = words.count
let odd = 0
for word in words {
let letters = word.map {
let letter = String($0)
if letter.isLower {
odd += 1
}
}
}
return .success(count == odd ? count : odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.isEmpty {
return .failure(0)
}
let count = words.count
let odd = 0
for word in words {
let letters = word.map {
let letter = String($0)
if letter.isLower {
odd += 1
}
}
}
return .success(count == odd ? count : odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.isEmpty {
return .failure(0)
}
let count = words.count
let odd = 0
for word in words {
let letters = word.map {
let letter = String($0)
if letter.isLower {
odd += 1
}
}
}
return .success(count == odd ? count : odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.isEmpty {
return .failure(0)
}
let count = words.count
let odd = 0
for word in words {
let letters = word.map {
let letter = String($0)
if letter.isLower {
odd += 1
}
}
}
return .success(count == odd ? count : odd)
}
// Given a string
if letter.isLower { // value of type 'String' has no member 'isLower'
return .success(count == odd ? count : odd) // cannot convert value of type 'Int' to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success(words)
}
return .success(words)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success(words)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success(words)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success(words)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success(words)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!
let letters = txt.count(for: .letter) // cannot call value of non-function type 'Int'
let letters = txt.count(for: .letter) // cannot infer contextual base in reference to member 'letter'
return .success(words) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
return .success(words) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(",") {
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } })
}
var count = 0
for char in txt {
if char.isLower && (char.unicodeScalarValue % 2) == 1 {
count += 1
}
}
return .failure(count)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(",") {
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } })
}
var count = 0
for char in txt {
if char.isLower && (char.unicodeScalarValue % 2) == 1 {
count += 1
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(",") {
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } })
}
var count = 0
for char in txt {
if char.isLower && (char.unicodeScalarValue % 2) == 1 {
count += 1
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(",") {
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } })
}
var count = 0
for char in txt {
if char.isLower && (char.unicodeScalarValue % 2) == 1 {
count += 1
}
}
return .failure(count)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(",") {
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } })
}
var count = 0
for char in txt {
if char.isLower &&
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } }) // reference to member 'trim' cannot be resolved without a contextual type
return .success(txt.split(separator: ",").map { $0.trim() }.map { $0.split(separator: " ").map { $0.trim() } }) // cannot infer type of closure parameter '$0' without a type annotation
if char.isLower && (char.unicodeScalarValue % 2) == 1 { // value of type 'Character' has no member 'isLower'
if char.isLower && (char.unicodeScalarValue % 2) == 1 { // value of type 'Character' has no member 'unicodeScalarValue'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let result = words.map {
let word = $0.trim()
if word.count == 0 {
return .failure(0)
}
return .success(word)
}
return .success(result)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let result = words.map {
let word = $0.trim()
if word.count == 0 {
return .failure(0)
}
return .success(word)
}
return .success(result)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let result = words.map {
let word = $0.trim()
if word.count == 0 {
return .failure(0)
}
return .success(word)
}
return .success(result)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let result = words.map {
let word = $0.trim()
if word.count == 0 {
return .failure(0)
}
return .success(word)
}
return .success(result)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let result = words.map {
let word = $0.trim()
if word.count == 0 {
return .failure(0)
}
return .success(word)
}
return .success(result)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet,
let word = $0.trim() // value of type 'String.SubSequence' (aka 'Substring') has no member 'trim'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 1 {
let letters = txt.count(for: .letter)
if letters % 2 == 1 {
return .failure(letters)
}
return .success([txt])
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!
let letters = txt.count(for: .letter) // cannot call value of non-function type 'Int'
let letters = txt.count(for: .letter) // cannot infer contextual base in reference to member 'letter'
return .success(words) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let odd = 0
for word in words {
let letters = word.split(separator: "")
for letter in letters {
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 {
odd += 1
}
}
}
return .success(odd)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let odd = 0
for word in words {
let letters = word.split(separator: "")
for letter in letters {
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 {
odd += 1
}
}
}
return .success(odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let odd = 0
for word in words {
let letters = word.split(separator: "")
for letter in letters {
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 {
odd += 1
}
}
}
return .success(odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let odd = 0
for word in words {
let letters = word.split(separator: "")
for letter in letters {
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 {
odd += 1
}
}
}
return .success(odd)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
let odd = 0
for word in words {
let letters = word.split(separator: "")
for letter in letters {
if letter.isLower && (letter.asciiValue - 97) %
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 { // value of type 'Substring.SubSequence' (aka 'Substring') has no member 'isLower'
if letter.isLower && (letter.asciiValue - 97) % 2 != 0 { // value of type 'Substring.SubSequence' (aka 'Substring') has no member 'asciiValue'
odd += 1 // left side of mutating operator isn't mutable: 'odd' is a 'let' constant
return .success(odd) // cannot convert value of type 'Int' to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
return .success(words)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no
return .success(words) // cannot convert value of type '[String.SubSequence]' (aka 'Array<Substring>') to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
var oddCount = 0
for word in words {
if word.count == 0 {
continue
}
for letter in word {
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 {
oddCount += 1
}
}
}
return .success(oddCount)
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
var oddCount = 0
for word in words {
if word.count == 0 {
continue
}
for letter in word {
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 {
oddCount += 1
}
}
}
return .success(oddCount)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
var oddCount = 0
for word in words {
if word.count == 0 {
continue
}
for letter in word {
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 {
oddCount += 1
}
}
}
return .success(oddCount)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
var oddCount = 0
for word in words {
if word.count == 0 {
continue
}
for letter in word {
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 {
oddCount += 1
}
}
}
return .success(oddCount)
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let words = txt.split(separator: " ")
if words.count == 0 {
return .failure(0)
}
var oddCount = 0
for word in words {
if word.count == 0 {
continue
}
for letter in word {
if letter.isLower
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
if letter.isLower && (letter.asciiValue - 97) % 2 == 1 { // value of type 'Substring.Element' (aka 'Character') has no member 'isLower'
return .success(oddCount) // cannot convert value of type 'Int' to expected argument type '[String]'
extension Int: Error {
}
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 })
} else if txt.contains(",") {
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 })
} else {
var count = 0
for char in txt {
if char.isLower && (char.asciiValue - 97) % 2 == 1 {
count += 1
}
}
return .failure(count)
}
}
```swift
extension Int: Error {
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 })
} else if txt.contains(",") {
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 })
} else {
var count = 0
for char in txt {
if char.isLower && (char.asciiValue - 97) % 2 == 1 {
count += 1
}
}
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 })
} else if txt.contains(",") {
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 })
} else {
var count = 0
for char in txt {
if char.isLower && (char.asciiValue - 97) % 2 == 1 {
count += 1
}
}
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
if txt.contains(" ") {
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 })
} else if txt.contains(",") {
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 })
} else {
var count = 0
for char in txt {
if char.isLower && (char.asciiValue - 97) % 2 == 1 {
count += 1
}
}
return .failure(count)
}
}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// split
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 }) // no exact matches in call to instance method 'split'
return .success(txt.split(" ").map { $0.trim() }.filter { $0.count > 0 }) // reference to member 'trim' cannot be resolved without a contextual type
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 }) // no exact matches in call to instance method 'split'
return .success(txt.split(",").map { $0.trim() }.filter { $0.count > 0 }) // reference to member 'trim' cannot be resolved without a contextual type
if char.isLower && (char.asciiValue - 97) % 2 == 1 { // value of type 'Character' has no member 'isLower'
if char.isLower && (char.asciiValue - 97) % 2 == 1 { // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i*2)
}
return newLst
}
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i/10)
}
return newLst
}
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i+10)
}
return newLst
}
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i+10+i*2)
}
return newLst
}
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
if i%2 == 0 {
newLst.append(i+10+i*2)
}
}
return newLst
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
// Given an array of numbers, return a new array with each number
// doubled.
// Examples
// map([1, 2, 3]) == [2, 4, 6]
// map([1, 2, 3, 4, 5]) == [2, 4, 6, 8, 10]
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i*2)
}
return newLst
}
// Given an array of numbers, return a new array with each number
// divided by 10.
// Examples
// map([1, 2, 3]) == [10, 20, 30]
// map([1, 2, 3, 4, 5]) == [10, 20, 30, 40, 50]
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i/10)
}
return newLst
}
// Given an array of numbers, return a new array with each number
// incremented by 10.
// Examples
// map([1, 2, 3]) == [11, 12, 13]
// map([1, 2, 3, 4, 5]) == [11, 12, 13, 14, 15]
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i+10)
}
return newLst
}
// Given an array of numbers, return a new array with each number
// doubled and incremented by 10.
// Examples
// map([1, 2, 3]) == [21, 22, 23]
// map([1, 2, 3, 4, 5]) == [21, 22, 23, 24, 25]
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
newLst.append(i+10+i*2)
}
return newLst
}
// Given an array of numbers, return a new array with each number
// doubled and incremented by 10, but only if the number is even.
// Examples
// map([1, 2, 3]) == [21, 22, 23]
// map([1, 2, 3, 4, 5]) == [21, 22, 23, 24, 25]
// map([1, 2, 3, 4, 5, 6]) == [21, 22, 23, 24, 25, 26]
func map(lst: [Int]) -> [Int] {
var newLst = []
for i in lst {
if i%2 == 0 {
newLst.append(i+10+i*2)
}
}
return newLst
}
// Given an array of numbers, return a new array with each number
// doubled and incremented by 10, but only if the number is even
// and less than 100.
// Examples
// map([1, 2, 3]) == [21, 22, 23]
// map([1, 2, 3, 4, 5]) == [21, 22, 23, 24, 25]
// map([1, 2, 3, 4, 5, 6]) == [21, 22, 23, 24, 25, 26]
// map([1, 2, 3, 4, 5
var newLst = [] // empty collection literal requires an explicit type
return newLst // cannot convert return expression of type '[Any]' to return type '[Int]'
func map(lst: [Int]) -> [Int] { // invalid redeclaration of 'map(lst:)'
var newLst = [] // empty collection literal requires an explicit type
return newLst // cannot convert return expression of type '[Any]' to return type '[Int]'
func map(lst: [Int]) -> [Int] { // invalid redeclaration of 'map(lst:)'
var newLst = [] // empty collection literal requires an explicit type
return newLst // cannot convert return expression of type '[Any]' to return type '[Int]'
func map(lst: [Int]) -> [Int] { // invalid redeclaration of 'map(lst:)'
var newLst = [] // empty collection literal requires an explicit type
return newLst // cannot convert return expression of type '[Any]' to return type '[Int]'
func map(lst: [Int]) -> [Int] { // invalid redeclaration of 'map(lst:)'
var newLst = [] // empty collection literal requires an explicit type
return newLst // cannot convert return expression of type '[Any]' to return type '[Int]'
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
var isSorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
isSorted = false
}
}
return isSorted
}
func firstTwo(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count < 2 {
return lst
}
return [lst[0], lst[1]]
}
func lastTwo(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count < 2 {
return lst
}
return [lst[lst.count-1], lst[lst.count-2]]
}
func firstHalf(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count % 2 == 0 {
return lst[0..<lst.count/2]
}
return lst[0..<(lst.count/2+1)]
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
var isSorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
isSorted = false
}
}
return isSorted
}
// -----------------------------------------------------------------------------
// 1.1
// Given an array of numbers, return a new array containing just the first
// two elements from the original array. If the original array has fewer
// than two elements, return an empty array.
// Examples
// firstTwo([1, 2, 3]) == [1, 2]
// firstTwo([1, 2]) == [1, 2]
// firstTwo([1]) == []
// firstTwo([]) == []
func firstTwo(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count < 2 {
return lst
}
return [lst[0], lst[1]]
}
// -----------------------------------------------------------------------------
// 1.2
// Given an array of numbers, return a new array containing just the last
// two elements from the original array. If the original array has fewer
// than two elements, return an empty array.
// Examples
// lastTwo([1, 2, 3]) == [3, 2]
// lastTwo([1, 2]) == [2, 1]
// lastTwo([1]) == []
// lastTwo([]) == []
func lastTwo(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count < 2 {
return lst
}
return [lst[lst.count-1], lst[lst.count-2]]
}
// -----------------------------------------------------------------------------
// 1.3
// Given an array of numbers, return a new array containing just the first
// half of the original array. If the original array has an odd number of
// elements, round down to the nearest element.
// Examples
// firstHalf([1, 2, 3, 4, 5]) == [1, 2, 3]
// firstHalf([1, 2, 3, 4]) == [1, 2, 3]
// firstHalf([1, 2, 3]) == [1, 2]
// firstHalf([1, 2]) == [1]
// firstHalf([1]) == [1]
// firstHalf([]) == []
func firstHalf(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count % 2 == 0 {
return lst[0..<lst.count/2]
}
return lst[0..<(lst.count/2+1)]
}
// -----------------------------------------------------------------------------
// 1.4
// Given an array of numbers, return a new array containing just the second
// half of the original array. If the original array has an odd number of
// elements, round up to the nearest element.
// Examples
// secondHalf([1, 2, 3, 4, 5]) == [4, 5]
// secondHalf([1, 2, 3, 4]) == [3, 4]
// secondHalf([1, 2, 3]) == [2, 3]
// secondHalf([1, 2]) == [1, 2]
// secondHalf([1]) == [1]
// secondHalf([]) == []
func secondHalf(lst: [Int]) -> [Int] {
if lst.count == 0 {
return []
}
if lst.count % 2 == 0 {
return lst
return lst[0..<lst.count/2] // cannot convert return expression of type 'ArraySlice<Int>' to return type '[Int]'
return lst[0..<(lst.count/2+1)] // cannot convert return expression of type 'ArraySlice<Int>' to return type '[Int]'
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
return false
}
}
return true
}
func indexOfLargest(lst: [Int]) -> Int {
var max = lst[0]
var index = 0
for i in 1..<lst.count {
if lst[i] > max {
max = lst[i]
index = i
}
}
return index
}
func indexOfSmallest(lst: [Int]) -> Int {
var min = lst[0]
var index = 0
for i in 1..<lst.count {
if lst[i] < min {
min = lst[i]
index = i
}
}
return index
}
func sum(lst: [Int]) -> Int {
var sum = 0
for i in lst {
sum += i
}
return sum
}
func average(lst: [Int]) -> Double {
return Double(sum(lst)) / Double(lst.count)
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return the index of the largest element.
// Assume non-empty array and all elements are numbers.
// Examples
// indexOfLargest([1, 2, 3]) == 2
// indexOfLargest([10, 4, 2, 231, 91, 5]) == 4
func indexOfLargest(lst: [Int]) -> Int {
var max = lst[0]
var index = 0
for i in 1..<lst.count {
if lst[i] > max {
max = lst[i]
index = i
}
}
return index
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return the index of the smallest element.
// Assume non-empty array and all elements are numbers.
// Examples
// indexOfSmallest([1, 2, 3]) == 0
// indexOfSmallest([10, 4, 2, 231, 91, 5]) == 2
func indexOfSmallest(lst: [Int]) -> Int {
var min = lst[0]
var index = 0
for i in 1..<lst.count {
if lst[i] < min {
min = lst[i]
index = i
}
}
return index
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return the sum of all elements.
// Assume non-empty array and all elements are numbers.
// Examples
// sum([1, 2, 3]) == 6
// sum([10, 4, 2, 231, 91, 5]) == 292
func sum(lst: [Int]) -> Int {
var sum = 0
for i in lst {
sum += i
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return the average of all elements.
// Assume non-empty array and all elements are numbers.
// Examples
// average([1, 2, 3]) == 2
// average([10, 4, 2, 231, 91, 5]) == 73.66666666666667
func average(lst: [Int]) -> Double {
return Double(sum(lst)) / Double(lst.count)
}
// -----------------------------------------------------------------------------
// ------
return Double(sum(lst)) / Double(lst.count) // missing argument label 'lst:' in call
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
func reverse(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += String(i)
}
return reversed
}
func evenNumbers(lst: [Int], number: Int) -> [Int] {
var even = []
for i in lst.reversed() {
if i % 2 == 0 {
even.append(i)
}
if even.count == number {
break
}
}
return even.reversed()
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given a string, return a new string with the reversed
// order of characters.
// Examples
// reverse("apple") == "elppa"
// reverse("hello") == "olleh"
// reverse("Greetings!") == "!sgniteerG"
func reverse(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += String(i)
}
return reversed
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return a new array
// of length number containing the last even numbers
// from the original array (in the same order).
// The original array will be not empty and will contain
// at least "number" even numbers.
// Examples
// evenNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == [6, 8, 9]
// evenNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) == [4, 6, 8, 9]
// evenNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 8) == [2, 4, 6, 8, 10, 12, 14, 16]
// evenNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 0) == []
func evenNumbers(lst: [Int], number: Int) -> [Int] {
var even = []
for i in lst.reversed() {
if i % 2 == 0 {
even.append(i)
}
if even.count == number {
break
}
}
return even.reversed()
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Given an array of numbers, return a new array
// of length number containing the last odd numbers
// from the original array (in the same order).
// The original array will be not empty and will contain
// at least "number" odd numbers.
// Examples
// oddNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == [5, 7, 9]
// oddNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) == [3, 5, 7, 9]
// oddNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 8) == [1, 3, 5, 7, 9, 11, 13, 15]
// oddNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 0) == []
func oddNumbers(lst: [Int], number: Int) -> [Int] {
var odd = []
for i in lst.reversed() {
if i % 2 != 0 {
odd.append(i)
}
if odd.count ==
var even = [] // empty collection literal requires an explicit type
return even.reversed() // no 'reversed' candidates produce the expected contextual result type '[Int]'
func isSorted(lst: [Int]) -> Bool {
if lst.count == 1 {
return true
}
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
return false
}
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count == 1 {
return true
}
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
return false
}
}
return true
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string
// reversed.
// Examples
// reverse("hello") == "olleh"
// reverse("hello world") == "dlrow olleh"
// reverse("12345") == "54321"
// reverse("") == ""
// reverse("h") == "h"
// reverse("a") == "a"
// reverse("aa") == "aa"
// reverse("aab") == "bba"
// reverse("aabb") == "bbaa"
// reverse("aabbcc") == "ccbbaa"
// reverse("aabbccdd") == "ddccbbaa"
// reverse("aabbccddff") == "ffddccbbaa"
// reverse("aabbccddffgg") == "ggffddccbbaa"
// reverse("aabbccddffgggg") == "ggggffddccbbaa"
// reverse("aabbccddffgggggg") == "ggggggffddccbbaa"
// reverse("aabbccddffgggggggg") == "ggggggggffddccbbaa"
// reverse("aabbccddffgggggggggg") == "ggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggg") == "ggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggg") == "ggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggg") == "ggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggg") == "ggggggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggggg") == "ggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggggg") == "ggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggggggg") == "ggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggggggg") == "ggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggggggggg") == "ggggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggggggggg") == "ggggggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggggggggggg") == "ggggggggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggggggggggg") == "ggggggggggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffgggggggggggggggggggggggg") == "ggggggggggggggggggggggggggggggggggggffddccbbaa"
// reverse("aabbccddffggggggggggggggggggggggggg") == "ggggggggggggggggggggggggggggggggggggggffddccbbaa"
// reverse("a
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 0..<lst.count-1 {
if lst[i] > lst[i+1] {
sorted = false
}
}
return sorted
}
// 2. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples
// removeVowels("Hello") == "Hll"
// removeVowels("abcdefghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("") == ""
// removeVowels("aeiou") == ""
// removeVowels("aeiouAEIOU") == ""
// removeVowels("abcedfghijklmnopqrstuvwxyz") == "bcdfghjklmnpqrstvwxyz"
// removeVowels("AEIOUaeiou") == ""
// removeVowels("AEIOUaeiou1234567890") == "1234567890"
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()") == "1234567890!@#$%^&*()"
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()?><,.") == "1234567890!@#$%^&*()?><,."
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()?><,.aeiouAEIOU") == "1234567890!@#$%^&*()?><,."
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()?><,.aeiouAEIOU1234567890!@#$%^&*()?><,.") == "1234567890!@#$%^&*()?><,."
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()?><,.aeiouAEIOU1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.") == "1234567890!@#$%^&*()?><,."
// removeVowels("AEIOUaeiou1234567890!@#$%^&*()?><,.aeiouAEIOU1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.AEIOUaeiou1234567890!@#$%^&*()?><,.
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
return lst.sorted() == lst
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
return lst.sorted() == lst
}
// Given an array of numbers, return the index of the largest number.
// If multiple numbers are tied for the largest value, return the index
// of the first one. Assume no empty arrays and no negative numbers.
// Examples
// indexOfLargest(lst: [1, 2, 3, 4, 5]) == 4
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6]) == 5
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7]) == 7
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8]) == 8
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9]) == 9
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 10
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 11
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 12
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 13
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 14
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 15
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 16
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 17
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 18
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 19
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == 20
// indexOfLargest(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
func reverse(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count == 0 {
return true
}
var sorted = true
for i in 0..<lst.count - 1 {
if lst[i] > lst[i + 1] {
sorted = false
}
}
return sorted
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// reversed.
// Examples
// reverse("hello") == "olleh"
// reverse("hello world") == "dlrow olleh"
// reverse("12345") == "54321"
// reverse("a") == "a"
// reverse("") == ""
// reverse("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "zyxwvutsrqponmlkjihgfedcba"
func reverse(s: String) -> String {
var reversed = ""
for i in s.reversed() {
reversed += i
}
return reversed
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string
// with all the spaces removed.
// Examples
// removeSpaces("hello world") == "helloworld"
// removeSpaces("hello world") == "helloworld"
// removeSpaces("") == ""
// removeSpaces("hello world!") == "helloworld!"
// removeSpaces("hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world! ") == "helloworld!"
// removeSpaces(" hello world!
reversed += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
// -----------------------------------------------------------------------------
// 2. Given an array of numbers, return the difference between the largest and
// smallest numbers in the array. Assume non-empty array and no negative
// numbers.
// Examples
// difference([1, 2, 3]) == 2
// difference([1, 2, 3, 4]) == 3
// difference([1, 2, 3, 4, 5]) == 4
// difference([1, 2, 3, 4, 5, 6]) == 5
// difference([1, 2, 3, 4, 5, 6, 7]) == 6
// difference([1, 2, 3, 4, 5, 6, 7, 8]) == 7
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 8
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 9
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 10
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 11
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 12
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 13
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 14
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 15
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 16
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 17
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 18
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == 19
// difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]) == 20
// difference([1, 2, 3
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i-1] {
sorted = false
}
}
return sorted
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a, b) = interval1
let (c, d) = interval2
let min = max(a, c)
let max = min(b, d)
if min > max {
return "NO"
}
let len = max - min
if len == 0 {
return "NO"
}
for i in 2...len {
if len % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a, b) = interval1
let (c, d) = interval2
let min = max(a, c)
let max = min(b, d)
if min > max {
return "NO"
}
let len = max - min
if len == 0 {
return "NO"
}
for i in 2...len {
if len % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// Task description
// -----------------------------------------------------------------------------
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two .
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a, b) = interval1
let (c, d) = interval2
let min = max(a, c)
let max = min(b, d)
if min > max {
return "NO"
}
let len = max - min
if len == 0 {
return "NO"
}
for i in 2...len {
if len % i == 0 {
return "NO"
}
}
return "YES"
}<|endoftext|>// -----------------------------------------------------------------------------
// Task description
// -----------------------------------------------------------------------------
// You are given a string of words. You need to find the word "Nemo",
// and return a string like this: "I found Nemo at [the order of the word you find nemo]!".
// If you can't find Nemo, return "I can't find Nemo :(".
// Example
// findNemo("I am finding Nemo !") should return "I found Nemo at 4!".
// findNemo("Nemo is me") should return "I found Nemo at 1!".
// findNemo("I Nemo am") should return "I found Nemo at 2!".
// findNemo("") should return "I can't find Nemo :(".
// findNemo("I am finding Nemo !") should return "I found Nemo at 4!".
// findNemo("Nemo is me") should return "I found Nemo at 1!".
// findNemo("I Nemo am") should return "I found Nemo at 2!".
// findNemo("") should return "I can't find Nemo :(".
// findNemo("I am finding Nemo !") should return "I found Nemo at 4!".
// findNemo("Nemo is me") should return "I found Nemo at 1!".
// findN
let max = min(b, d) // cannot call value of non-function type 'Int'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a1, b1) = interval1
let (a2, b2) = interval2
let a = max(a1, a2)
let b = min(b1, b2)
if a > b {
return "NO"
}
let len = b - a
if len < 0 {
return "NO"
}
let isPrime = true
for i in 2...len {
if len % i == 0 {
isPrime = false
break
}
}
if isPrime {
return "YES"
}
return "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a1, b1) = interval1
let (a2, b2) = interval2
let a = max(a1, a2)
let b = min(b1, b2)
if a > b {
return "NO"
}
let len = b - a
if len < 0 {
return "NO"
}
let isPrime = true
for i in 2...len {
if len % i == 0 {
isPrime = false
break
}
}
if isPrime {
return "YES"
}
return "NO"
}
// -----------------------------------------------------------------------------
// 1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
isPrime = false // cannot assign to value: 'isPrime' is a 'let' constant
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// [task description]
// -----------------------------------------------------------------------------
// You are given a string s.
// Your task is to check if the string is palindrome or not.
// A string is said to be palindrome if it is equal to itself when reversed.
// Example:
// s = "abba"
// The string is a palindrome.
// s = "abc"
// The string is not a palindrome.
// [input/output] samples:
// isPalindrome("abba") == true
// isPalindrome("abc") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// -----------------------------------------------------------------------------
// [task description]
// -----------------------------------------------------------------------------
// You are given a string s.
// Your task is to check if the string is palindrome or not.
// A string is said to be palindrome if it is equal to itself when reversed.
// Example:
// s = "abba"
// The string is a palindrome.
// s = "abc"
// The string is not a palindrome.
// [input/output] samples:
// isPalindrome("abba") == true
// isPalindrome("abc") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// -----------------------------------------------------------------------------
// [task description]
// -----------------------------------------------------------------------------
// You are given a string s.
// Your task is to check if the string is palindrome or not.
// A string is said to be palindrome if it is equal to itself when reversed.
// Example:
// s = "abba"
// The string is a palindrome.
// s = "abc"
// The string is not a palindrome.
// [input/output] samples:
// isPalindrome("abba") == true
// isPalindrome("abc") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// -----------------------------------------------------------------------------
// [task description]
// -----------------------------------------------------------------------------
// You are given a string s.
// Your task is to check if the string is palindrome or not.
// A string is said to be palindrome if it is equal to itself when reversed.
// Example:
// s = "abba"
// The string is a palindrome.
// s = "abc"
// The string is not a palindrome.
// [input/output] samples:
// isPalindrome("abba") == true
// isPalindrome("abc") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// -----------------------------------------------------------------------------
// [task description]
// ------
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start
if length < 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start
if length < 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// Task description
// -----------------------------------------------------------------------------
//
// You are given a string of words. You need to find the word "Nemo",
// and return a string like this: "I found Nemo at [the order of the word he appears]!".
// If you can't find Nemo, return "I can't find Nemo :(".
//
// Example
//
// findNemo("I am finding Nemo !") should return "I found Nemo at 4!".
// findNemo("I am findNemo !") should return "I found Nemo at 1!".
// findNemo("I am FindNemo !") should return "I found Nemo at 1!".
// findNemo("I am FindNemo !") should return "I found Nemo at 1!".
// findNemo("I am findNemo !") should return "I found Nemo at 1!".
// findNemo("I am find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found Nemo at 1!".
// findNemo("I am Find nemo !") should return "I found
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// Task description
// -----------------------------------------------------------------------------
// You are given a string.
// Your task is to check if the string is palindrome or not.
// A string is said to be a palindrome if it is same after reverse.
// Example
// For inputString = "abcdba", the output should be
// isPalindrome(inputString) = true;
// For inputString = "abcbade", the output should be
// isPalindrome(inputString) = false.
// Input/Output
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// Solution
// -----------------------------------------------------------------------------
// You can use the built-in function `reverse` to reverse a string.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// A string consisting of lowercase latin letters.
// Guaranteed constraints:
// 3 ≤ inputString.length ≤ 10.
// [output] boolean
// true if inputString is a palindrome, false otherwise.
// -----------------------------------------------------------------------------
// [input] string inputString
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func capitalizeEven(s: String) -> String {
var result = ""
for i in 0..<s.length {
let c = s[i]
if i % 2 == 0 {
result += c.uppercaseString
} else {
result += c.lowercaseString
}
}
return result
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start
if length <= 1 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// [input/output] samples:
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("ab") == "ba"
// reverseString("abc") == "cba"
// reverseString("abcd") == "dcba"
// reverseString("abcde") == "edcba"
// reverseString("abcdefg") == "gfedcba"
// reverseString("abcdefghijklmnopqrstuvwxyz") == "zyxwvutsrqponmlkjihgfedcba"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string with
// all the even characters capitalized and all the odd characters small.
// Example:
// Given s = "abcdefg", return "abCedg".
// [input/output] samples:
// capitalizeEven("abcdefg") == "abCedg"
// capitalizeEven("") == ""
// capitalizeEven("a") == "a"
// capitalizeEven("ab") == "Ab"
// capitalizeEven("abc") == "AbC"
// capitalizeEven("abcd") == "AbCd"
// capitalizeEven("abcde") == "AbCdE"
// capitalizeEven("abcdefg") == "AbCedg"
// capitalizeEven("abcdefghijklmnopqrstuvwxyz") == "AbCedgHijklmnopqrstuvwxyz"
func capitalizeEven(s: String) -> String {
var result = ""
for i in 0..<s.length {
let c = s[i]
if i % 2 == 0 {
result += c.uppercaseString
} else {
result += c.lowercaseString
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string with
// all the even characters capitalized and all the odd characters small.
// Example:
// Given s = "abcdefg", return "abCedg".
// [input/output] samples:
// capitalizeEven("abcdefg") == "abCedg"
// capitalizeEven("") == ""
// capitalizeEven("a") == "a"
// capitalizeEven("ab") == "Ab"
// capitalizeEven("abc") == "AbC"
// capitalizeEven("abcd") == "AbCd"
// capitalizeEven("abcde") == "AbCdE"
// capitalizeEven("abcdefg") == "AbCedg"
// capitalizeEven("abcdefghijklmnopqrstuvwxyz") == "AbCedgHijklmnopqrstuvwxyz"
func capitalizeEven(s: String) -> String {
var result = ""
for i in 0..
for i in 0..<s.length { // value of type 'String' has no member 'length'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a, b) = interval1
let (c, d) = interval2
let min = max(a, c)
let max = min(b, d)
let length = max - min
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a, b) = interval1
let (c, d) = interval2
let min = max(a, c)
let max = min(b, d)
let length = max - min
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// [input/output] samples:
// reverseString("hello") == "olleh"
// reverseString("12345") == "54321"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("ha") == "ah"
// reverseString("hello world") == "dlrow olleh"
// reverseString("123456789") == "987654321"
// reverseString("1234567890") == "0987654321"
// reverseString("12345678901") == "10987654321"
// reverseString("123456789012") == "210987654321"
// reverseString("1234567890123") == "3210987654321"
// reverseString("12345678901234") == "43210987654321"
// reverseString("123456789012345") == "543210987654321"
// reverseString("1234567890123456") == "6543210987654321"
// reverseString("12345678901234567")
// reverseString("123456789012345678")
// reverseString("1234567890123456789")
// reverseString("12345678901234567890")
// reverseString("123456789012345678901")
// reverseString("1234567890123456789012")
// reverseString("12345678901234567890123")
// reverseString("123456789012345678901234")
// reverseString("1234567890123456789012345")
// reverseString("12345678901234567890123456")
// reverseString("123456789012345678901234567")
// reverseString("1234567890123456789012345678")
// reverseString("12345678901234567890123456789")
// reverseString("123456789012345678901234567890")
// reverseString("1234567
let max = min(b, d) // cannot call value of non-function type 'Int'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2..<length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// [input/output] samples:
// reverseString("hello") == "olleh"
// reverseString("") == ""
// reverseString("h") == "h"
// reverseString("a") == "a"
// reverseString("a b c") == "c b a"
// reverseString("a b c d e f g h i j k l m n o p q r s t u v w x y z") == "z y x w v u t s r q p o n m l k j i h g f e d c b a"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example:
// The binary representation of 5 is 101 (in base-10), so the return value should be 2.
// Note:
// Note that in some languages such as Java, there is no unsigned integer type.
// In this case, the input will be given as a signed integer type.
// It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
// [input/output] samples:
// countBits(5) == 2
// countBits(0) == 0
// countBits(1) == 1
// countBits(2) == 1
// countBits(3) == 2
// countBits(4) == 1
// countBits(5) == 2
// countBits(6) == 2
// countBits(7) == 3
// countBits(8) == 1
// countBits(9) == 2
// countBits(10) == 2
// countBits(11) == 3
// countBits(12) == 2
// countBits(13) == 3
// countBits(14) == 3
// countBits(15) == 4
// countBits(16) == 1
// countBits(17) == 2
// countBits(18) == 2
// countBits(19) == 3
// countBits(20) == 2
// countBits(21) == 3
// countBits(22) == 3
// countBits(23) == 4
// countBits(24) == 1
// countBits(25) == 2
// countBits(26) == 2
// countBits(27) == 3
// countBits(28) == 3
// countBits(29) == 4
// countBits(30) == 1
// countBits(31) == 2
// countBits(32) == 1
// countBits(33) == 2
// countBits(34) == 2
// countBits(35) == 3
// countBits(36) == 2
// countBits(37) == 3
// countBits(38) == 3
// countBits(39) == 4
// countBits(40) == 1
// countBits(41) == 2
// countBits(42) == 2
// countBits(43) == 3
// countBits(44) ==
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a1, b1) = interval1
let (a2, b2) = interval2
let a = max(a1, a2)
let b = min(b1, b2)
if a > b {
return "NO"
}
let len = b - a
if len < 0 {
return "NO"
}
var isPrime = true
for i in 2...len {
if len % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (a1, b1) = interval1
let (a2, b2) = interval2
let a = max(a1, a2)
let b = min(b1, b2)
if a > b {
return "NO"
}
let len = b - a
if len < 0 {
return "NO"
}
var isPrime = true
for i in 2...len {
if len % i == 0 {
isPrime = false
break
}
}
return isPrime ? "YES" : "NO"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
for i in 2...length {
if length % i == 0 {
return "NO"
}
}
return "YES"
}
// -----------------------------------------------------------------------------
// 1.2.1.3.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.
// Fatal error: Range requires lowerBound <= upperBound
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
func sum(a: Int, b: Int) -> Int {
if a == b {
return a
}
if a < b {
return (a + 1) * (b - a) / 2
}
return (b + 1) * (a - b) / 2
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/55f2b114941f82c5db0000a3/train/swift
// Given two integers a and b, which can be positive or negative,
// find the sum of all the integers between and including them
// and return it. If the two numbers are equal return a or b.
// Note: a and b are not ordered!
// Examples (a, b) --> output (explanation)
// (1, 2) --> 3 (1 + 2)
// (1, 1) --> 1 (1 + 1)
// (1, 0) --> 1 (1 + 0)
// (0, 0) --> 0 (0 + 0)
// (0, 1) --> 1 (0 + 1)
func sum(a: Int, b: Int) -> Int {
if a == b {
return a
}
if a < b {
return (a + 1) * (b - a) / 2
}
return (b + 1) * (a - b) / 2
}
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/55f2b114941f81a77b0000d3/train/swift
// Given two integers a and b, which can be positive or negative,
// find the sum of all the integers between and including them
// and return it. If the two numbers are equal return a or b.
// Note: a and b are not ordered!
// Examples (a, b) --> output (explanation)
// (1, 2) --> 3 (1 + 2)
// (1, 1) --> 1 (1 + 1)
// (1, 0) --> 1 (1 + 0)
// (0, 0) --> 0 (0 + 0)
// (0, 1) --> 1 (0 + 1)
func sum(a: Int, b: Int) -> Int {
if a == b {
return a
}
if a < b {
return (a + 1) * (b - a) / 2
}
return (b + 1) * (a - b) / 2
}
// -----------------------------------------------------------------------------
// https://www.codewars.com/kata/55f2b863d63c2e6abcd00003c/train/swift
// Given two integers a and b, which can be positive or negative,
// find the sum of all the integers between and including them
// and return it. If the two numbers are equal return a or b.
// Note: a and b are not ordered!
// Examples (a, b) --> output (explanation)
// (1, 2) --> 3 (1 + 2)
// (1, 1) --> 1 (1 + 1)
// (1, 0) --> 1 (1 + 0)
// (0, 0) --> 0 (0 + 0)
// (0, 1) --> 1 (0 + 1)
func sum(a: Int, b: Int) -> Int {
if a == b {
return a
}
if a < b {
return (a + 1) * (b - a) / 2
}
return (b + 1) * (a -
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
func longestSubstring(s: String) -> Int {
var max = 0
var start = 0
var map = [Int: Int]()
for i in range(0, s.count) {
if map[s[i]] != nil {
start = max(start, map[s[i]] + 1)
}
max = max(max, i - start + 1)
map[s[i]] = i
}
return max
}
func longestPalindrome(s: String) -> String {
var max = ""
for i in range(0, s.count) {
for j in range(i, s.count) {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// 2.
// Given a string, find the length of the longest substring without repeating characters.
// Example:
// longestSubstring("abcabcbb") == 3
// longestSubstring("bbbbb") == 1
// longestSubstring("pwwkew") == 3
func longestSubstring(s: String) -> Int {
var max = 0
var start = 0
var map = [Int: Int]()
for i in range(0, s.count) {
if map[s[i]] != nil {
start = max(start, map[s[i]] + 1)
}
max = max(max, i - start + 1)
map[s[i]] = i
}
return max
}
// 3.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example:
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in range(0, s.count) {
for j in range(i, s.count) {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 4.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example:
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in range(0, s.count) {
for j in range(i, s.count) {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 5.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example:
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in range(0, s.count) {
for j in range(i, s.count) {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > max.count {
max = sub
}
}
}
}
return max
}
// 6.
// Given a string s, find the longest palindromic substring in s.
// You may assume that the maximum length of s is 1000.
// Example:
// longestPalindrome("babad") == "bab"
// longestPalindrome("cbbd") == "bb"
func longestPalindrome(s: String) -> String {
var max = ""
for i in range(0, s.count) {
for j in range(i, s.count) {
var sub = s[i..<j]
if sub == sub.reversed() {
if sub.count > max.count {
max = sub
}
}
for i in range(0, s.count) { // cannot find 'range' in scope
for i in range(0, s.count) { // cannot find 'range' in scope
for j in range(i, s.count) { // cannot find 'range' in scope
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
let sum = 0
let product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += 1
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
let sum = 0
let product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += 1
}
return sum * product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
product *= -1 // left side of mutating operator isn't mutable: 'product' is a 'let' constant
sum += 1 // left side of mutating operator isn't mutable: 'sum' is a 'let' constant
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += 1
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += 1
}
return sum * product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------------
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
sum += 1
} else if i > 0 {
product *= i
} else {
product *= -i
}
}
return sum == 0 ? 0 : product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
sum += 1
} else if i > 0 {
product *= i
} else {
product *= -i
}
}
return sum == 0 ? 0 : product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i < 0 {
product *= -1
}
sum += i
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i < 0 {
product *= -1
}
sum += i
}
return sum * product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i > 0 {
sum += 1
}
if i < 0 {
product *= -1
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i > 0 {
sum += 1
}
if i < 0 {
product *= -1
}
}
return sum * product
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given an array of integers, find the one that appears an odd number of times.
// There will always be only one integer that appears an odd number of times.
// Examples
// [7] should return 7, because it occurs 1 time (which is odd).
// [0] should return 0, because it occurs 1 time (which is odd).
// [1,1,2] should return 2, because it occurs 1 time (which is odd).
// [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).
// [1,2,2,3,3,3] should return 3.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
product = 0
} else if i > 0 {
sum *= i
} else {
sum *= -i
}
}
return sum * product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 1
var product = 1
for i in arr {
if i == 0 {
product = 0
} else if i > 0 {
sum *= i
} else {
sum *= -i
}
}
return sum * product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i < 0 {
sum += 1
}
product *= i
}
return sum % 2 == 0 ? product : -product
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
return 0
}
if i < 0 {
sum += 1
}
product *= i
}
return sum % 2 == 0 ? product : -product
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
struct MagnitudeProduct {
var sum: Int
var product: Int
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
struct MagnitudeProduct {
var sum: Int
var product: Int
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var product = 1
for i in arr {
if i == 0 {
continue
}
if i < 0 {
product *= -1
}
sum += abs(i)
}
return sum * product
}
// -----------------------------------------------------------------------------
func prodSigns(arr: [Int]) -> Int? {
if arr.count == 0 {
return nil
}
var sum = 0
var
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count,
value: [Int](count: grid.count, value: -1))
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 0
}
}
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
break
}
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if 0 <= nx && nx < grid.count && 0 <= ny && ny < grid.count &&
visited[nx][ny] == -1 {
visited[nx][ny] = step + 1
queue.enqueue((nx, ny, step + 1))
}
}
}
return result
}
import Foundation
func maxProfit(prices: [Int]) -> Int {
var result = 0
var minPrice = Int.max
for price in prices {
minPrice = min(minPrice, price)
result = max(result, price - minPrice)
}
return result
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count,
value: [Int](count: grid.count, value: -1))
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 0
}
}
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
break
}
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if 0 <= nx && nx < grid.count && 0 <= ny && ny < grid.count &&
visited[nx][ny] == -1 {
visited[nx][ny] = step + 1
queue.enqueue((nx, ny, step + 1))
}
}
}
return result
}<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 윤선우 on 2021/08/23.
//
import Foundation
func maxProfit(prices: [Int]) -> Int {
var result = 0
var minPrice = Int.max
for price in prices {
minPrice = min(minPrice, price)
result = max(result, price - minPrice)
}
return result
}
var prices = [7,1,5,3,6,4]
print(maxProfit(prices: prices))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 윤선우 on 2021/08/23.
//
import Foundation
func maxProfit(prices: [Int]) -> Int {
var result = 0
var minPrice = Int.max
for price in prices {
minPrice = min(minPrice, price)
result = max(result, price - minPrice)
}
return result
}
var prices = [7,1,5,3,6,4]
print(maxProfit(prices: prices))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 윤선우 on 2021/08/23.
//
import Foundation
func maxProfit(prices: [Int]) -> Int {
var result = 0
var minPrice = Int.max
for price in prices {
minPrice = min(minPrice, price)
result = max(result, price - minPrice)
}
return result
}
var prices = [7,1,5,3,6,4]
print(maxProfit(prices: prices))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 윤선우 on 2021/08/23.
//
import Foundation
func maxProfit(prices: [Int]) -> Int {
var result = 0
var minPrice = Int.max
for price in prices {
minPrice = min(minPrice, price)
result = max(result, price - minPrice)
}
return result
}
var prices = [7,1,5,3,6,4]
print(maxProfit(prices: prices))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 윤선우 on 2021/08/23.
//
import Foundation
func maxProfit(pr
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
var visited = [[Int]](count: grid.count, // no exact matches in call to initializer
value: [Int](count: grid.count, value: -1)) // no exact matches in call to initializer
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count, value: 0)
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 1
}
}
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid.count {
continue
}
if visited[nx][ny] == 1 {
continue
}
visited[nx][ny] = 1
queue.enqueue((nx, ny, step + 1))
}
}
return result
}
import Foundation
class Solution {
func isPalindrome(_ s: String) -> Bool {
var i = 0
var j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
func partition(_ s: String) -> [[String]] {
var result = [[String]]()
var temp = [String]()
var i = 0
while i < s.count {
var j = i
while j < s.count {
temp.append(s[i...j])
if isPalindrome(temp.joined()) {
result.append(temp)
}
temp.removeLast()
j += 1
}
temp.removeLast()
i += 1
}
return result
}
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count, value: 0)
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 1
}
}
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid.count {
continue
}
if visited[nx][ny] == 1 {
continue
}
visited[nx][ny] = 1
queue.enqueue((nx, ny, step + 1))
}
}
return result
}<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 임주민 on 2021/04/10.
//
import Foundation
class Solution {
func isPalindrome(_ s: String) -> Bool {
var i = 0
var j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
func partition(_ s: String) -> [[String]] {
var result = [[String]]()
var temp = [String]()
var i = 0
while i < s.count {
var j = i
while j < s.count {
temp.append(s[i...j])
if isPalindrome(temp.joined()) {
result.append(temp)
}
temp.removeLast()
j += 1
}
temp.removeLast()
i += 1
}
return result
}
}
let solution = Solution()
print(solution.partition("aab"))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 임주민 on 2021/04/10.
//
import Foundation
class Solution {
func isPalindrome(_ s: String) -> Bool {
var i = 0
var j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
func partition(_ s: String) -> [[String]] {
var result = [[String]]()
var temp = [String]()
var i = 0
while i < s.count {
var j = i
while j < s.count {
temp.append(s[i...j])
if isPalindrome(temp.joined()) {
result.append(temp)
}
temp.removeLast()
j += 1
}
temp.removeLast()
i += 1
}
return result
}
}
let solution = Solution()
print(solution.partition("aab"))<|endoftext|>//
// main.swift
// LeetCode
//
// Created by 임주민 on 2021/04/10.
//
import Foundation
class Solution {
func isPalindrome(_ s: String) -> Bool {
var i = 0
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
var visited = [[Int]](count: grid.count, value: 0) // no exact matches in call to initializer
if s[i] != s[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != s[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
temp.append(s[i...j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var visited = [Int]()
var queue = [[Int]]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append([i, j])
visited.append(1)
}
}
}
while queue.count > 0 {
var temp = queue.pop()
var i = temp[0]
var j = temp[1]
if result.count == k {
break
}
if i > 0 && visited[i - 1] == 0 {
queue.append([i - 1, j])
visited[i - 1] = 1
}
if i < grid.count - 1 && visited[i + 1] == 0 {
queue.append([i + 1, j])
visited[i + 1] = 1
}
if j > 0 && visited[j - 1] == 0 {
queue.append([i, j - 1])
visited[j - 1] = 1
}
if j < grid[i].count - 1 && visited[j + 1] == 0 {
queue.append([i, j + 1])
visited[j + 1] = 1
}
result.append(grid[i][j])
}
return result
}
import Foundation
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func findPrime(num: Int) -> Int {
var count = 0
var i = 1
while count < num {
i += 1
if isPrime(i) {
count += 1
}
}
return i
}
func main() {
print(findPrime(10001))
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var visited = [Int]()
var queue = [[Int]]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
queue.append([i, j])
visited.append(1)
}
}
}
while queue.count > 0 {
var temp = queue.pop()
var i = temp[0]
var j = temp[1]
if result.count == k {
break
}
if i > 0 && visited[i - 1] == 0 {
queue.append([i - 1, j])
visited[i - 1] = 1
}
if i < grid.count - 1 && visited[i + 1] == 0 {
queue.append([i + 1, j])
visited[i + 1] = 1
}
if j > 0 && visited[j - 1] == 0 {
queue.append([i, j - 1])
visited[j - 1] = 1
}
if j < grid[i].count - 1 && visited[j + 1] == 0 {
queue.append([i, j + 1])
visited[j + 1] = 1
}
result.append(grid[i][j])
}
return result
}<|endoftext|>//
// main.swift
// 10001stPrime
//
// Created by 임현민 on 2021/01/05.
//
import Foundation
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func findPrime(num: Int) -> Int {
var count = 0
var i = 1
while count < num {
i += 1
if isPrime(i) {
count += 1
}
}
return i
}
func main() {
print(findPrime(10001))
}
main()<|endoftext|>//
// main.swift
// 10001stPrime
//
// Created by 임현민 on 2021/01/05.
//
import Foundation
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func findPrime(num: Int) -> Int {
var count = 0
var i = 1
while count < num {
i += 1
if isPrime(i) {
count += 1
}
}
return i
}
func main() {
print(findPrime(10001))
}
main()<|endoftext|>//
// main.swift
// 10001stPrime
//
// Created by 임현민 on 2021/01/05.
//
import Foundation
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
func findPrime(num: Int) -> Int {
var count = 0
var i = 1
while count < num {
i += 1
if isPrime(i) {
count += 1
}
}
return i
}
func main
var temp = queue.pop() // value of type '[[Int]]' has no member 'pop'
if isPrime(i) { // missing argument label 'num:' in call
print(findPrime(10001)) // missing argument label 'num:' in call
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
var dp = Array<[Int]>(count: k + 1)
for i in 1...k {
dp[i] = Array<Int>(count: n)
for j in 0..<n {
for d in -1..<2 {
let x = j + d
if x < 0 || x >= n {
continue
}
let y = dp[i - 1][x]
if y == 0 {
continue
}
dp[i][j] = max(dp[i][j], y + grid[j][x])
}
}
}
var res = Array<Int>(count: k)
for i in 0..<n {
res[k - 1] = dp[k][i]
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
var dp = Array<[Int]>(count: k + 1)
for i in 1...k {
dp[i] = Array<Int>(count: n)
for j in 0..<n {
for d in -1..<2 {
let x = j + d
if x < 0 || x >= n {
continue
}
let y = dp[i - 1][x]
if y == 0 {
continue
}
dp[i][j] = max(dp[i][j], y + grid[j][x])
}
}
}
var res = Array<Int>(count: k)
for i in 0..<n {
res[k - 1] = dp[k][i]
}
return res
}
// 2022-09-22 15:26:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:31:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:35:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:39:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:43:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:47:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:51:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 15:55:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 16:00:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 16:05:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 16:10:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22 16:15:08
// 100 / 100 test cases passed.
// Status: Accepted
// Runtime: 128 ms
// Memory Usage: 51.4 MB
//
// 2022-09-22
var dp = Array<[Int]>(count: k + 1) // missing argument for parameter 'repeating' in call
dp[i] = Array<Int>(count: n) // missing argument for parameter 'repeating' in call
var res = Array<Int>(count: k) // missing argument for parameter 'repeating' in call
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
queue.enqueue((0, 0, 0))
var visited = Array<Array<Bool>>(count: grid.count)
for i in 0..<grid.count {
visited[i] = Array<Bool>(count: grid[i].count)
}
while !queue.isEmpty {
var (x, y, count) = queue.dequeue()
if count == k {
result.append(grid[x][y])
return result
}
visited[x][y] = true
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid[nx].count {
continue
}
if visited[nx][ny] {
continue
}
queue.enqueue((nx, ny, count + 1))
}
}
return result
}
import Foundation
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
queue.enqueue((0, 0, 0))
var visited = Array<Array<Bool>>(count: grid.count)
for i in 0..<grid.count {
visited[i] = Array<Bool>(count: grid[i].count)
}
while !queue.isEmpty {
var (x, y, count) = queue.dequeue()
if count == k {
result.append(grid[x][y])
return result
}
visited[x][y] = true
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid[nx].count {
continue
}
if visited[nx][ny] {
continue
}
queue.enqueue((nx, ny, count + 1))
}
}
return result
}
var grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
var k = 3
print(minPath(grid: grid, k: k))
var grid = [[5, 9, 3], [4, 1, 6], [7, 8, 2]]
var k = 1
print(minPath(grid: grid, k: k))<|endoftext|>//
// main.swift
// 1004
//
// Created by 임명환 on 2020/04/08.
// Copyright © 2020 임명환. All rights reserved.
//
import Foundation
// 1004. Max Consecutive Ones III
// https://leetcode.com/problems/max-consecutive-ones-iii/
// Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
// Return the length of the longest (contiguous) subarray that contains only 1s.
//
// Example 1:
// Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
// Output: 6
// Explanation:
// [1,1,1,0,0,1,1,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
//
// Example 2:
// Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
// Output: 10
// Explanation:
// [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
// Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
//
// Note:
// 1 <= A.length <= 20000
// 0 <= K <= A.length
// A[i] is 0 or 1
// 처음 생각한 방법
// 연속된 1의 개수를 세고, 최대 개수를 찾는 방법
// 연속된 1의 개수가 K보다 작으면 연속된 1의 개수를 센다.
// 연속된 1의 개수가 K보다 �������
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
var visited = Array<Array<Bool>>(count: grid.count) // missing argument for parameter 'repeating' in call
visited[i] = Array<Bool>(count: grid[i].count) // missing argument for parameter 'repeating' in call
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [Int: Bool]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
visited[grid[i][j]] = false
}
}
queue.enqueue((0, 0, 0))
visited[grid[0][0]] = true
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid[nx].count {
continue
}
if visited[grid[nx][ny]] {
continue
}
visited[grid[nx][ny]] = true
queue.enqueue((nx, ny, step + 1))
}
}
return result
}
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i * i
}
print(result)
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [Int: Bool]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
visited[grid[i][j]] = false
}
}
queue.enqueue((0, 0, 0))
visited[grid[0][0]] = true
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid[nx].count {
continue
}
if visited[grid[nx][ny]] {
continue
}
visited[grid[nx][ny]] = true
queue.enqueue((nx, ny, step + 1))
}
}
return result
}<|endoftext|>//
// main.swift
// 1024
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}<|endoftext|>//
// main.swift
// 1025
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i * i
}
print(result)
}<|endoftext|>//
// main.swift
// 1026
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}<|endoftext|>//
// main.swift
// 1027
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}<|endoftext|>//
// main.swift
// 1028
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}<|endoftext|>//
// main.swift
// 1029
//
// Created by 임명호 on 2021/08/09.
//
import Foundation
func main() {
var n = Int(readLine()!)!
var result = 0
for i in 1...n {
result += i
}
print(result)
}<|endoftext|>//
// main.swift
// 1030
//
// Created by 임명호 on 2021/08
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
if visited[grid[nx][ny]] { // value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
var n = Int(readLine()!)! // variable 'n' was never mutated; consider changing to 'let' constant
func main() { // invalid redeclaration of 'main()'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = [[Int]]()
var visited = [[Int]]()
var path = [Int]()
var min = Int.max
for i in 0..<grid.count {
for j in 0..<grid[i].count {
queue.append([i, j])
visited.append([i, j])
}
}
while queue.count > 0 {
var current = queue.popLast()
path.append(grid[current[0]][current[1]])
if path.count == k {
if path.sum() < min {
min = path.sum()
result = path
}
}
var neighbors = [[Int]]()
if current[0] > 0 {
neighbors.append([current[0] - 1, current[1]])
}
if current[0] < grid.count - 1 {
neighbors.append([current[0] + 1, current[1]])
}
if current[1] > 0 {
neighbors.append([current[0], current[1] - 1])
}
if current[1] < grid[current[0]].count - 1 {
neighbors.append([current[0], current[1] + 1])
}
for neighbor in neighbors {
if !visited.contains(neighbor) {
queue.append(neighbor)
visited.append(neighbor)
}
}
path.removeLast()
}
return result
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = [[Int]]()
var visited = [[Int]]()
var path = [Int]()
var min = Int.max
for i in 0..<grid.count {
for j in 0..<grid[i].count {
queue.append([i, j])
visited.append([i, j])
}
}
while queue.count > 0 {
var current = queue.popLast()
path.append(grid[current[0]][current[1]])
if path.count == k {
if path.sum() < min {
min = path.sum()
result = path
}
}
var neighbors = [[Int]]()
if current[0] > 0 {
neighbors.append([current[0] - 1, current[1]])
}
if current[0] < grid.count - 1 {
neighbors.append([current[0] + 1, current[1]])
}
if current[1] > 0 {
neighbors.append([current[0], current[1] - 1])
}
if current[1] < grid[current[0]].count - 1 {
neighbors.append([current[0], current[1] + 1])
}
for neighbor in neighbors {
if !visited.contains(neighbor) {
queue.append(neighbor)
visited.append(neighbor)
}
}
path.removeLast()
}
return result
}
// 2022-10-24 11:17:30
// 1.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 100.00
// 10
path.append(grid[current[0]][current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
path.append(grid[current[0]][current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
if path.sum() < min { // value of type '[Int]' has no member 'sum'
min = path.sum() // value of type '[Int]' has no member 'sum'
if current[0] > 0 { // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0] - 1, current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0] - 1, current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
if current[0] < grid.count - 1 { // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0] + 1, current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0] + 1, current[1]]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
if current[1] > 0 { // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0], current[1] - 1]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0], current[1] - 1]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
if current[1] < grid[current[0]].count - 1 { // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
if current[1] < grid[current[0]].count - 1 { // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0], current[1] + 1]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
neighbors.append([current[0], current[1] + 1]) // value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [Int: Int]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
queue.enqueue((i, j, 0))
visited[grid[i][j]] = 0
}
}
while !queue.isEmpty {
var (i, j, step) = queue.dequeue()
if step == k {
result.append(grid[i][j])
break
}
for (di, dj) in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
var ni = i + di
var nj = j + dj
if ni < 0 || ni >= grid.count || nj < 0 || nj >= grid[ni].count {
continue
}
var n = grid[ni][nj]
if visited[n] == nil || visited[n] > step + 1 {
visited[n] = step + 1
queue.enqueue((ni, nj, step + 1))
}
}
}
return result
}
func longestPalindrome(s: String) -> String {
var result = ""
var dp = [String: Bool]()
for i in 0..<s.count {
dp[s[i]] = true
}
for i in 0..<s.count {
var j = i
while j >= 0 {
var sub = s[j..<i]
if sub.length == 1 {
dp[sub] = true
} else if sub.length == 2 {
dp[sub] = dp[sub[0]] && dp[sub[1]]
} else {
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]]
}
if dp[sub] && sub.length > result.length {
result = sub
}
j -= 1
}
}
return result
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [Int: Int]()
for i in 0..<grid.count {
for j in 0..<grid[i].count {
queue.enqueue((i, j, 0))
visited[grid[i][j]] = 0
}
}
while !queue.isEmpty {
var (i, j, step) = queue.dequeue()
if step == k {
result.append(grid[i][j])
break
}
for (di, dj) in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
var ni = i + di
var nj = j + dj
if ni < 0 || ni >= grid.count || nj < 0 || nj >= grid[ni].count {
continue
}
var n = grid[ni][nj]
if visited[n] == nil || visited[n] > step + 1 {
visited[n] = step + 1
queue.enqueue((ni, nj, step + 1))
}
}
}
return result
}
// 10.10
// Given a string, find the length of the longest substring without repeating
// characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is "wke", with the length of 3. Note that the
// answer must be a substring, "pwke" is a subsequence and not a substring.
// 10.11
// Given a string s, find the longest palindromic substring in s. You may assume
// that the maximum length of s is 1000.
// Examples:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var result = ""
var dp = [String: Bool]()
for i in 0..<s.count {
dp[s[i]] = true
}
for i in 0..<s.count {
var j = i
while j >= 0 {
var sub = s[j..<i]
if sub.length == 1 {
dp[sub] = true
} else if sub.length == 2 {
dp[sub] = dp[sub[0]] && dp[sub[1]]
} else {
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]]
}
if dp[sub] && sub.length > result.length {
result = sub
}
j -= 1
}
}
return result
}
// 10.12
// Given a string s, partition s such that every substring of the partition is a
// palindrome.
// Return all possible palindrome partitioning of s.
// For example, given s = "aab",
// Return
// [
// ["aa","b"],
// ["a","a","b"]
// ]
// 10.13
// Given a string s, partition s such that every substring of the partition is a
// palindrome.
// Return all possible palindrome partitioning of s.
// For example, given s = "aab",
// Return
// [
// ["aa","b"],
// ["a","a","b"]
// ]
// 10.14
// Given a string s, partition s such that every substring of the partition is a
// palindrome.
// Return all possible palindrome partitioning of s.
// For example, given s = "aab",
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
if visited[n] == nil || visited[n] > step + 1 { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
dp[s[i]] = true // cannot convert value of type 'Character' to expected argument type 'String'
var sub = s[j..<i] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if sub.length == 1 { // value of type 'String' has no member 'length'
} else if sub.length == 2 { // value of type 'String' has no member 'length'
dp[sub] = dp[sub[0]] && dp[sub[1]] // value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
dp[sub] = dp[sub[0]] && dp[sub[1]] // no exact matches in call to subscript
dp[sub] = dp[sub[0]] && dp[sub[1]] // cannot convert value of type 'Character' to expected argument type 'String'
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]] // value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]] // cannot convert value of type 'Character' to expected argument type 'String'
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]] // optional type 'Bool?' cannot be used as a boolean; test for '!= nil' instead
dp[sub] = dp[sub[0]] && dp[sub[1]] && dp[sub[2..<i]] // no exact matches in call to subscript
if dp[sub] && sub.length > result.length { // value of type 'String' has no member 'length'
if dp[sub] && sub.length > result.length { // value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
if dp[sub] && sub.length > result.length { // value of type 'String' has no member 'length'
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count,
value: [Int](count: grid.count,
value: -1))
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 0
}
}
}
while !queue.isEmpty {
var (x, y, dist) = queue.dequeue()
if dist == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid.count {
continue
}
if visited[nx][ny] != -1 {
continue
}
visited[nx][ny] = dist + 1
queue.enqueue((nx, ny, dist + 1))
}
}
return result
}
func longestPalindrome(s: String) -> String {
var dp = [[Bool]](count: s.count,
value: [Bool](count: s.count,
value: false))
var result = ""
for i in 0..<s.count {
dp[i][i] = true
result = s[i]
}
for i in 0..<s.count - 1 {
if s[i] == s[i + 1] {
dp[i][i + 1] = true
result = s[i..<i + 2]
}
}
for length in 3..<s.count {
for i in 0..<s.count - length {
if dp[i + 1][i + length - 1] && s[i] == s[i + length] {
dp[i][i + length] = true
result = s[i..<i + length + 1]
}
}
}
return result
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
var visited = [[Int]](count: grid.count,
value: [Int](count: grid.count,
value: -1))
for i in 0..<grid.count {
for j in 0..<grid.count {
if grid[i][j] == 1 {
queue.enqueue((i, j, 0))
visited[i][j] = 0
}
}
}
while !queue.isEmpty {
var (x, y, dist) = queue.dequeue()
if dist == k {
result.append(grid[x][y])
return result
}
for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
var nx = x + dx
var ny = y + dy
if nx < 0 || nx >= grid.count || ny < 0 || ny >= grid.count {
continue
}
if visited[nx][ny] != -1 {
continue
}
visited[nx][ny] = dist + 1
queue.enqueue((nx, ny, dist + 1))
}
}
return result
}
var grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
var k = 3
print(minPath(grid: grid, k: k))
var grid = [[5, 9, 3], [4, 1, 6], [7, 8, 2]]
var k = 1
print(minPath(grid: grid, k: k))<|endoftext|>// Given a string s, return the longest palindromic substring in s.
// Example 1:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: s = "cbbd"
// Output: "bb"
// Example 3:
// Input: s = "a"
// Output: "a"
// Example 4:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
// 1. 动态规划
// 时间复杂度:O(n^2)
// 空间复杂度:O(n^2)
func longestPalindrome(s: String) -> String {
var dp = [[Bool]](count: s.count,
value: [Bool](count: s.count,
value: false))
var result = ""
for i in 0..<s.count {
dp[i][i] = true
result = s[i]
}
for i in 0..<s.count - 1 {
if s[i] == s[i + 1] {
dp[i][i + 1] = true
result = s[i..<i + 2]
}
}
for length in 3..<s.count {
for i in 0..<s.count - length {
if dp[i + 1][i + length - 1] && s[i] == s[i + length] {
dp[i][i + length] = true
result = s[i..<i + length + 1]
}
}
}
return result
}
var s = "babad"
print(longestPalindrome(s: s))
var s = "cbbd"
print(longestPalindrome(s: s))
var s = "a"
print(longestPalindrome(s: s))
var s = "ac"
print(longestPalindrome(s: s))<|endoftext|>// Given an integer array nums, return the number of longest increasing subsequences.
// Notice that the sequence has to be
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
var visited = [[Int]](count: grid.count, // no exact matches in call to initializer
value: [Int](count: grid.count, // no exact matches in call to initializer
var dp = [[Bool]](count: s.count, // no exact matches in call to initializer
value: [Bool](count: s.count, // no exact matches in call to initializer
result = s[i] // cannot assign value of type 'Character' to type 'String'
if s[i] == s[i + 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] == s[i + 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = s[i..<i + 2] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
result = s[i..<i + length + 1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
queue.enqueue((0, 0, 0))
var visited = Array<Array<Bool>>(count: grid.count)
for i in 0..<grid.count {
visited[i] = Array<Bool>(count: grid[i].count)
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
if x > 0 && !visited[x - 1][y] {
visited[x - 1][y] = true
queue.enqueue((x - 1, y, step + 1))
}
if x < grid.count - 1 && !visited[x + 1][y] {
visited[x + 1][y] = true
queue.enqueue((x + 1, y, step + 1))
}
if y > 0 && !visited[x][y - 1] {
visited[x][y - 1] = true
queue.enqueue((x, y - 1, step + 1))
}
if y < grid[x].count - 1 && !visited[x][y + 1] {
visited[x][y + 1] = true
queue.enqueue((x, y + 1, step + 1))
}
}
return result
}
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var start = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] != nil {
start = max(start, map[s[i]]! + 1)
}
map[s[i]] = i
result = max(result, i - start + 1)
}
return result
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
var result = [Int]()
var queue = Queue<(Int, Int, Int)>()
queue.enqueue((0, 0, 0))
var visited = Array<Array<Bool>>(count: grid.count)
for i in 0..<grid.count {
visited[i] = Array<Bool>(count: grid[i].count)
}
while !queue.isEmpty {
var (x, y, step) = queue.dequeue()
if step == k {
result.append(grid[x][y])
return result
}
if x > 0 && !visited[x - 1][y] {
visited[x - 1][y] = true
queue.enqueue((x - 1, y, step + 1))
}
if x < grid.count - 1 && !visited[x + 1][y] {
visited[x + 1][y] = true
queue.enqueue((x + 1, y, step + 1))
}
if y > 0 && !visited[x][y - 1] {
visited[x][y - 1] = true
queue.enqueue((x, y - 1, step + 1))
}
if y < grid[x].count - 1 && !visited[x][y + 1] {
visited[x][y + 1] = true
queue.enqueue((x, y + 1, step + 1))
}
}
return result
}
// 12. Given a string s, find the length of the longest substring without repeating
// characters.
// Examples:
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var start = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] != nil {
start = max(start, map[s[i]]! + 1)
}
map[s[i]] = i
result = max(result, i - start + 1)
}
return result
}
// 13. Given a string s, find the length of the longest substring without repeating
// characters.
// Examples:
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(s: String) -> Int {
var result = 0
var start = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] != nil {
start = max(start, map[s[i]]! + 1)
}
map[s[i]] = i
result = max(result, i - start + 1)
}
return result
}
// 14. Given an array of integers, return indices of the two numbers such that they
// add up to a specific target.
// You may assume that each input would have exactly one solution, and you may
// not use the same element twice.
// Examples:
// twoSum([2, 7, 11, 15], 9) == [0, 1]
// twoSum([3, 2, 4], 6) == [1, 2]
// twoSum([3, 3], 6) == [0, 1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var map = [Int: Int]()
for i in 0..<nums.count {
if map[target - nums[i]] !
var queue = Queue<(Int, Int, Int)>() // cannot find 'Queue' in scope
var visited = Array<Array<Bool>>(count: grid.count) // missing argument for parameter 'repeating' in call
visited[i] = Array<Bool>(count: grid[i].count) // missing argument for parameter 'repeating' in call
if map[s[i]] != nil { // cannot convert value of type 'Character' to expected argument type 'Int'
start = max(start, map[s[i]]! + 1) // cannot convert value of type 'Character' to expected argument type 'Int'
map[s[i]] = i // cannot convert value of type 'Character' to expected argument type 'Int'
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
struct Tribonacci_80_1: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_2: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_3: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_4: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_5: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_6: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_7: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_8: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
}
struct Tribonacci_80_1: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_2: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_3: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_4: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_5: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_6: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_7: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_8: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12])
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20])
}
}
struct Tribonacci_80_9: Tests {
func test() {
XCTAssertEqual(tri(3), [1, 3, 2, 8])
XCTAssertEqual(tri(4), [
struct Tribonacci_80_1: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_2: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_3: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_4: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_5: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_6: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_7: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
struct Tribonacci_80_8: Tests { // cannot find type 'Tests' in scope
XCTAssertEqual(tri(3), [1, 3, 2, 8]) // missing argument label 'n:' in call
XCTAssertEqual(tri(4), [1, 3, 2, 8, 12]) // missing argument label 'n:' in call
XCTAssertEqual(tri(5), [1, 3, 2, 8, 12, 20]) // missing argument label 'n:' in call
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(result[i - 1] + (i / 2))
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(result[i - 1] + (i / 2))
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// Task description
// You are given a non-negative integer number n.
// You have to return a sequence of integers with the following properties:
// The first element of the sequence is equal to 1.
// The second element of the sequence is equal to 2.
// Every next element of the sequence is equal to the sum of the previous three elements.
// The sequence has to contain n elements.
// Examples:
// tribonacci(3) == [1, 2, 4]
// tribonacci(7) == [1, 2, 4, 7, 13, 24, 44]
// tribonacci(25) == [1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1669, 3044, 5673, 10399, 18697, 31481, 57474, 108918, 198611, 369024, 661030, 1239029, 213070519, 331233301]
// Note:
// The sequence should be represented as a list of integers.
// The first element of the sequence is 1.
// The second element of the sequence is 2.
// The third element of the sequence is 4.
// The fourth element of the sequence is 7.
// The fifth element of the sequence is 13.
// The sixth element of the sequence is 24.
// The seventh element of the sequence is 44.
// The eighth element of the sequence is 81.
// The ninth element of the sequence is 149.
// The tenth element of the sequence is 274.
// The eleventh element of the sequence is 504.
// The twelfth element of the sequence is 927.
// The thirteenth element of the sequence is 1669.
// The fourteenth element of the sequence is 3044.
// The fifteenth element of the sequence is 5673.
// The sixteenth element of the sequence is 10399.
// The seventeenth element of the sequence is 18697.
// The eighteenth element of the sequence is 31481.
// The nineteenth element of the sequence is 57474.
// The twentieth element of the sequence is 108918.
// The twenty-first element of the sequence is 198611.
// The twenty-second element of the sequence is 369024.
// The twenty-third element of the sequence is 661030.
// The twenty-fourth element of the sequence is 1239029.
// The twenty-fifth element of the sequence is 213070519.
// The twenty-sixth element of the sequence is 331233301.
// The twenty-seventh element of the sequence is 530619500.
// The twenty-eighth element of the sequence is 863245350.
// The twenty-ninth element of the sequence is 1486726700.
// The thirtieth element of the sequence is 2631476400.
// The thirt-first element of the sequence is 4613876300.
// The thirt-second element of the sequence is 7507510600.
// The thirt-third element of the sequence is 12166333925.
// The thirt-fourth element of the sequence is
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 1...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) == 1
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
//}
//{swift
// Given a non-negative integer number, return the sum of its digits.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(1234) == 10
// sumDigits(999) == 27
// sumDigits(1000) ==
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return result
}
if n == 1 {
return result
}
if n == 2 {
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return result
}
if n == 1 {
return result
}
if n == 2 {
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// 2.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 3.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 4.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 5.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 6.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 7.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
// Good Luck!
// Note:
// The input string will only contain lower case letters and numbers.
//
// 8.
// Given a string, you have to return a string in which each character (case-sensitive)
// is repeated once.
// Examples (Input -> Output):
// * "String" -> "SSttrriinngg"
// * "Hello World" -> "HHeelllloo WWoorrlldd"
// * "1234!_ " -> "11223344!!__ "
//
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 2
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 3
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 4
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 5
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 6
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i-1] + result[i-2])
} else {
result.append(result[i-1] + result[i-2] + result[i-3])
}
}
return result
}
// Task 7
// You are given a non-negative integer number n, you have to return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
for i in 1..<n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
// Fatal error: Index out of range
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map { Int($0) }
for digit in digits {
if digit % 2 != 0 {
result *= digit
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map { Int($0) }
for digit in digits {
if digit % 2 != 0 {
result *= digit
}
}
return result
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// For example:
// vowels("apple") == 2
// vowels("banana") == 3
// vowels("grapefruit") == 5
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi") == 0
// vowels("kiwi
var digits = String(n).map { Int($0) } // no exact matches in call to initializer
var digits = String(n).map { Int($0) } // no exact matches in call to initializer
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map { Int(String($0))! }
for digit in digits {
if digit % 2 == 1 {
result *= digit
}
}
return result
}
func vowels(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
func words(string: String) -> Int {
var result = 0
for _ in string {
result += 1
}
return result
}
func consonants(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
continue
}
result += 1
}
return result
}
func uppercase(string: String) -> Int {
var result = 0
for char in string {
if char == char.uppercase {
result += 1
}
}
return result
}
func lowercase(string: String) -> Int {
var result = 0
for char in string {
if char == char.lowercase {
result += 1
}
}
return result
}
func digits(string: String) -> Int {
var result = 0
for char in string {
if char == "0" || char == "1" || char == "2" || char == "3" || char == "4" || char == "5" || char == "6" || char == "7" || char == "8" || char == "9" {
result += 1
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map { Int(String($0))! }
for digit in digits {
if digit % 2 == 1 {
result *= digit
}
}
return result
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// For example:
// vowels("Hello world") == 3
// vowels("aeiou") == 5
// vowels("") == 0
func vowels(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
// 3. Write a function that takes a string as input and returns the number of words in the string.
// For example:
// words("Hello world") == 2
// words("Hello world, how are you?") == 4
// words("") == 0
func words(string: String) -> Int {
var result = 0
for _ in string {
result += 1
}
return result
}
// 4. Write a function that takes a string as input and returns the number of consonants in the string.
// For example:
// consonants("Hello world") == 5
// consonants("aeiou") == 0
// consonants("") == 0
func consonants(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
if char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
continue
}
result += 1
}
return result
}
// 5. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// For example:
// uppercase("Hello world") == 2
// uppercase("Hello World") == 2
// uppercase("") == 0
func uppercase(string: String) -> Int {
var result = 0
for char in string {
if char == char.uppercase {
result += 1
}
}
return result
}
// 6. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// For example:
// lowercase("Hello world") == 5
// lowercase("Hello World") == 5
// lowercase("") == 0
func lowercase(string: String) -> Int {
var result = 0
for char in string {
if char == char.lowercase {
result += 1
}
}
return result
}
// 7. Write a function that takes a string as input and returns the number of digits in the string.
// For example:
// digits("Hello world") == 0
// digits("12345") == 5
// digits("") == 0
func digits(string: String) -> Int {
var result = 0
for char in string {
if char == "0" || char == "1" || char == "2" || char == "3" || char == "4" || char == "5" || char == "6" || char == "7" || char == "8" || char == "9" {
result += 1
}
}
return result
}
// 8. Write a function that takes a string as input and returns the number of words that start with a vowel.
// For example:
// vowels("Hello world") == 1
// vowels("Hello World") == 1
// vowels("") == 0
func vowels(string: String) -> Int {
var result = 0
for char
var digits = String(n).map { Int(String($0))! } // variable 'digits' was never mutated; consider changing to 'let' constant
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
return result
}
func trim(s: String) -> String {
var result = ""
var i = 0
while i < s.length && s[i] == " " {
i += 1
}
while i < s.length {
result += s[i]
i += 1
}
return result
}
func trimAlpha(s: String) -> String {
var result = ""
var i = 0
while i < s.length && s[i].isAlpha {
result += s[i]
i += 1
}
while i < s.length {
if s[i].isAlpha {
result += s[i]
}
i += 1
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string reversed.
// For example:
// reverse("hello") == "olleh"
// reverse("hello world") == "dlrow olleh"
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string with all capital letters converted to lowercase and vice versa.
// For example:
// swapCase("Hello, World!") == "hELLO, wORLD!"
// swapCase("HELLO, WORLD!") == "hello, world!"
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string with leading and trailing whitespace removed.
// For example:
// trim(" Hello, World! ") == "Hello, World!"
// trim("Hello, World!") == "Hello, World!"
// trim("") == ""
func trim(s: String) -> String {
var result = ""
var i = 0
while i < s.length && s[i] == " " {
i += 1
}
while i < s.length {
result += s[i]
i += 1
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the string with leading and trailing whitespace removed, and all non-alphabetic characters removed.
// For example:
// trimAlpha(" Hello, World! ") == "Hello, World"
// trimAlpha("Hello, World!") == "Hello, World"
// trimAlpha("") == ""
// trimAlpha("1234567890") == ""
func trimAlpha(s: String) -> String {
var result = ""
var i = 0
while i < s.length && s[i].isAlpha {
result += s[i]
i += 1
}
while i < s.length {
if s[i].isAlpha {
result += s[i]
}
i += 1
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string with leading and trailing whitespace removed, and all non-alphabetic characters removed, and all consecutive whitespace characters converted to a single space.
// For example:
// trimAlpha(" Hello, World! ") == "Hello, World"
// trimAlpha("Hello, World!") == "Hello, World"
// trimAlpha("") == ""
// trimAlpha("1234567890") == ""
// trimAlpha("Hello, World!") == "Hello, World"
func trimAlpha(s: String) -> String {
var result = ""
var i = 0
while i < s.length && s[i].is
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lower // value of type 'Character' has no member 'lower'
result += char.upper // value of type 'Character' has no member 'upper'
while i < s.length && s[i] == " " { // value of type 'String' has no member 'length'
while i < s.length { // value of type 'String' has no member 'length'
result += s[i] // no exact matches in call to subscript
while i < s.length && s[i].isAlpha { // value of type 'String' has no member 'length'
while i < s.length && s[i].isAlpha { // value of type 'Character' has no member 'isAlpha'
result += s[i] // no exact matches in call to subscript
while i < s.length { // value of type 'String' has no member 'length'
if s[i].isAlpha { // value of type 'Character' has no member 'isAlpha'
result += s[i] // no exact matches in call to subscript
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init)
for digit in digits {
if digit.isAsciiLetter {
result *= digit.value
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init)
for digit in digits {
if digit.isAsciiLetter {
result *= digit.value
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a positive integer n, return the product of the digits.
// If the product is greater than 10, repeat the process until the product is
// a single-digit integer.
// For example:
// digits(n: 1234) == 1
// digits(n: 12345) == 120
// digits(n: 123456) == 240
// digits(n: 1234567) == 240
// digits(n: 12345678) == 240
// digits(n: 123456789) == 240
// digits(n: 1234567890) == 240
// digits(n: 12345678901) == 240
// digits(n: 123456789012) == 240
// digits(n: 1234567890123) == 240
// digits(n: 12345678901234) == 240
// digits(n: 123456789012345) == 240
// digits(n: 1234567890123456) == 240
// digits(n: 12345678901234567) == 240
// digits(n: 123456789012345678) == 240
// digits(n: 1234567890123456789) == 240
// digits(n: 12345678901234567890) == 240
// digits(n: 123456789012345678901) == 240
// digits(n: 1234567890123456789012) == 240
// digits(n: 12345678901234567890123) == 240
// digits(n: 123456789012345678901234) == 240
// digits(n: 1234567890123456789012345) == 240
// digits(n: 12345678901234567890123456) == 240
// digits(n: 123456789012345678901234567) == 240
// digits(n: 1234567890123456789012345678) == 240
// digits(n: 12345678901234567890123456789) == 240
// digits(n: 123456789012345678901234567890) == 240
// digits(n: 1234567890123456789012345678901) == 240
// digits(n: 12345678901234567890123
if digit.isAsciiLetter { // value of type 'Character' has no member 'isAsciiLetter'
result *= digit.value // value of type 'Character' has no member 'value'
func digits(n: Int) -> Int {
var product = 1
var isOdd = false
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
product *= digit
isOdd = true
}
n /= 10
}
return isOdd ? product : 0
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var product = 1
var isOdd = false
while n > 0 {
let digit = n % 10
if digit % 2 != 0 {
product *= digit
isOdd = true
}
n /= 10
}
return isOdd ? product : 0
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
n /= 10 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init)
for digit in digits {
if digit.isAsciiLetter {
result *= digit.value
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init)
for digit in digits {
if digit.isAsciiLetter {
result *= digit.value
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
if digit.isAsciiLetter { // value of type 'Character' has no member 'isAsciiLetter'
result *= digit.value // value of type 'Character' has no member 'value'
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
result *= digit
}
num /= 10
}
return result
}
func vowels(s: String) -> Int {
var result = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
result += 1
default:
break
}
}
return result
}
func words(s: String) -> Int {
var result = 0
var word = ""
for char in s {
if char == " " {
result += 1
word = ""
} else {
word += char
}
}
return result + 1
}
func consonants(s: String) -> Int {
var result = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
break
default:
result += 1
}
}
return result
}
func uppercase(s: String) -> Int {
var result = 0
for char in s {
if char == char.uppercase {
result += 1
}
}
return result
}
func lowercase(s: String) -> Int {
var result = 0
for char in s {
if char == char.lowercase {
result += 1
}
}
return result
}
func digits(s: String) -> Int {
var result = 0
for char in s {
if char.isDigit {
result += 1
}
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
result *= digit
}
num /= 10
}
return result
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// For example:
// vowels("hello") == 2
// vowels("apple") == 2
// vowels("banana") == 3
func vowels(s: String) -> Int {
var result = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
result += 1
default:
break
}
}
return result
}
// 3. Write a function that takes a string as input and returns the number of words in the string.
// For example:
// words("hello world") == 2
// words("apple pie") == 2
// words("banana bread") == 3
func words(s: String) -> Int {
var result = 0
var word = ""
for char in s {
if char == " " {
result += 1
word = ""
} else {
word += char
}
}
return result + 1
}
// 4. Write a function that takes a string as input and returns the number of consonants in the string.
// For example:
// consonants("hello") == 3
// consonants("apple") == 4
// consonants("banana") == 6
func consonants(s: String) -> Int {
var result = 0
for char in s {
switch char {
case "a", "e", "i", "o", "u":
break
default:
result += 1
}
}
return result
}
// 5. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// For example:
// uppercase("Hello") == 1
// uppercase("apple") == 0
// uppercase("BANANA") == 3
func uppercase(s: String) -> Int {
var result = 0
for char in s {
if char == char.uppercase {
result += 1
}
}
return result
}
// 6. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// For example:
// lowercase("Hello") == 5
// lowercase("apple") == 5
// lowercase("BANANA") == 0
func lowercase(s: String) -> Int {
var result = 0
for char in s {
if char == char.lowercase {
result += 1
}
}
return result
}
// 7. Write a function that takes a string as input and returns the number of digits in the string.
// For example:
// digits("hello") == 0
// digits("apple") == 0
// digits("12345") == 5
func digits(s: String) -> Int {
var result = 0
for char in s {
if char.isDigit {
result += 1
}
}
return result
}
// 8. Write a function that takes a string as input and returns the number of words that start with a vowel.
// For example:
// vowelWords("hello world") == 1
// vowelWords("apple pie") == 1
// vowelWords("banana bread") == 2
func vowelWords(s: String) -> Int {
var result = 0
var word = ""
for char in s {
if char == " " {
if word.first!.isVowel {
result += 1
}
word = "
word += char // cannot convert value of type 'Character' to expected argument type 'String'
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
result *= digit
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 != 0 {
result *= digit
}
num /= 10
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init).map(Character.isDigit)
for digit in digits {
if digit {
result *= digit
}
}
return result
}
func sumNumbers(input: String) -> Int {
var result = 0
var digits = input.map(Character.init).map(Character.isDigit)
var currentNumber = ""
for digit in digits {
if digit {
currentNumber += String(digit)
} else {
if currentNumber.length > 0 {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber.length > 0 {
result += Int(currentNumber)
}
return result
}
func maxBlock(input: String) -> Int {
var result = 0
var currentBlock = ""
var currentLength = 0
for char in input {
if char == currentBlock.last! {
currentLength += 1
} else {
currentBlock = String(char)
currentLength = 1
}
result = max(result, currentLength)
}
return result
}
func maxRun(input: String) -> Int {
var result = 0
var currentRun = ""
var currentLength = 0
for char in input {
if char == currentRun.last! {
currentLength += 1
} else {
currentRun = String(char)
currentLength = 1
}
result = max(result, currentLength)
}
return result
}
func longestSubstring(input: String) -> String {
var result = ""
var currentSubstring = ""
var currentLength = 0
var currentIndex = 0
while currentIndex < input.length {
var char = input[currentIndex]
if currentSubstring.contains(char) {
if currentLength < currentSubstring.length {
result = currentSubstring
}
currentSubstring = ""
currentLength = 0
currentIndex = 0
} else {
currentSubstring += char
currentLength += 1
currentIndex += 1
}
}
if currentLength > result.length {
result = currentSubstring
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var digits = String(n).map(Character.init).map(Character.isDigit)
for digit in digits {
if digit {
result *= digit
}
}
return result
}
// 2.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// For example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 56y 3") == 7563
func sumNumbers(input: String) -> Int {
var result = 0
var digits = input.map(Character.init).map(Character.isDigit)
var currentNumber = ""
for digit in digits {
if digit {
currentNumber += String(digit)
} else {
if currentNumber.length > 0 {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber.length > 0 {
result += Int(currentNumber)
}
return result
}
// 3.
// Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same.
// For example:
// maxBlock("hoopla") == 3
// maxBlock("abbCCCddBBBxx") == 3
// maxBlock("") == 0
func maxBlock(input: String) -> Int {
var result = 0
var currentBlock = ""
var currentLength = 0
for char in input {
if char == currentBlock.last! {
currentLength += 1
} else {
currentBlock = String(char)
currentLength = 1
}
result = max(result, currentLength)
}
return result
}
// 4.
// Given a string, return the length of the longest "run" of chars. A run is a series of chars that are adjacent and identical.
// For example:
// maxRun("hoopla") == 3
// maxRun("abbCCCddBBBxx") == 3
// maxRun("") == 0
func maxRun(input: String) -> Int {
var result = 0
var currentRun = ""
var currentLength = 0
for char in input {
if char == currentRun.last! {
currentLength += 1
} else {
currentRun = String(char)
currentLength = 1
}
result = max(result, currentLength)
}
return result
}
// 5.
// Given a string, return the longest substring with no duplicate chars.
// For example:
// longestSubstring("abcabcbb") == "abc"
// longestSubstring("bbbbb") == "b"
// longestSubstring("pwwkew") == "wke"
func longestSubstring(input: String) -> String {
var result = ""
var currentSubstring = ""
var currentLength = 0
var currentIndex = 0
while currentIndex < input.length {
var char = input[currentIndex]
if currentSubstring.contains(char) {
if currentLength < currentSubstring.length {
result = currentSubstring
}
currentSubstring = ""
currentLength = 0
currentIndex = 0
} else {
currentSubstring += char
currentLength += 1
currentIndex += 1
}
}
if currentLength > result.length {
result = currentSubstring
}
return result
}
// 6.
// Given a string, return the longest palindromic substring.
// For example:
// longestPalindrome("ab
var digits = String(n).map(Character.init).map(Character.isDigit) // type 'Character' has no member 'isDigit'
var digits = String(n).map(Character.init).map(Character.isDigit) // generic parameter 'T' could not be inferred
var digits = input.map(Character.init).map(Character.isDigit) // type 'Character' has no member 'isDigit'
var digits = input.map(Character.init).map(Character.isDigit) // generic parameter 'T' could not be inferred
if currentNumber.length > 0 { // value of type 'String' has no member 'length'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
while currentIndex < input.length { // value of type 'String' has no member 'length'
var char = input[currentIndex] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if currentLength < currentSubstring.length { // value of type 'String' has no member 'length'
currentSubstring += char // cannot convert value of type 'Character' to expected argument type 'String'
if currentLength > result.length { // value of type 'String' has no member 'length'
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let digit = num % 10
if digit % 2 == 1 {
result *= digit
}
num /= 10
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
switch char {
case "[":
stack.append(char)
case "]":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
switch char {
case "[":
stack.append(char)
case "]":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels are the letters 'a', 'e', 'i', 'o', and 'u'.
// countVowels(string: "Hello world!") == 3
// countVowels(string: "apple") == 2
// countVowels(string: "") == 0
// countVowels(string: "aeiou") == 5
// countVowels(string: "AEIOU") == 5
// countVowels(string: "AeIou") == 5
// countVowels(string: "Aeiou") == 5
// countVowels(string: "AeiouAeiou") == 10
// countVowels(string: "AeiouAeiouAeiou") == 15
// countVowels(string: "AeiouAeiouAeiouAeiou") == 20
// countVowels(string: "AeiouAeiouAeiouAeiouAeiou") == 25
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiou") == 30
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 35
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 40
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 45
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 50
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 55
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 60
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 65
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 70
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou") == 75
// countVowels(string: "AeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiouAeiou"
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append("[")
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String]()
for char in string {
if char == "[" {
stack.append("[")
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
print(isNested("[[]]"))
print(isNested("[]]]]]]][[[[[]"))
print(isNested("[][]"))
print(isNested("[]"))
print(isNested("[[][]]"))
print(isNested("[[]][["))
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[String]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
switch char {
case "[":
stack.append("[")
case "]":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
func countLetters(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
switch char {
case "[":
stack.append("[")
case "]":
if stack.isEmpty {
return false
}
stack.pop()
default:
break
}
}
return stack.isEmpty
}
// ----------------------------------------------------------------------------------------------------------------------
// 2. Create a function that takes a string as input and returns the number of times the letter "a" appears in the string.
// countLetters(string: "apple") == 2
// countLetters(string: "banana") == 3
// countLetters(string: "grapefruit") == 5
// countLetters(string: "orange") == 1
// countLetters(string: "kiwi") == 1
// countLetters(string: "pineapple") == 2
// countLetters(string: "strawberry") == 3
// countLetters(string: "watermelon") == 2
// countLetters(string: "") == 0
func countLetters(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 3. Create a function that takes a string as input and returns the number of times the letter "a" appears in the string.
// countLetters(string: "apple") == 2
// countLetters(string: "banana") == 3
// countLetters(string: "grapefruit") == 5
// countLetters(string: "orange") == 1
// countLetters(string: "kiwi") == 1
// countLetters(string: "pineapple") == 2
// countLetters(string: "strawberry") == 3
// countLetters(string: "watermelon") == 2
// countLetters(string: "") == 0
func countLetters(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 4. Create a function that takes a string as input and returns the number of times the letter "a" appears in the string.
// countLetters(string: "apple") == 2
// countLetters(string: "banana") == 3
// countLetters(string: "grapefruit") == 5
// countLetters(string: "orange") == 1
// countLetters(string: "kiwi") == 1
// countLetters(string: "pineapple") == 2
// countLetters(string: "strawberry") == 3
// countLetters(string: "watermelon") == 2
// countLetters(string: "") == 0
func countLetters(string: String) -> Int {
var count = 0
for char in string {
if char == "a" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 5. Create a function that takes a string as input and returns the number of times the letter "a" appears in the string.
// countLetters(string: "apple") == 2
// countLetters(string: "banana") == 3
// countLetters(string: "grapefruit") == 5
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func countNested(string: String) -> Int {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
continue
}
stack.pop()
count += 1
}
}
return count
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// 2. Create a function that takes a string as input which contains only square brackets.
// The function should return the number of valid subsequences of brackets.
// countNested(string: "[[]]") == 2
// countNested(string: "[]]]]]]][[[[[]") == 0
// countNested(string: "[][]") == 0
// countNested(string: "[]") == 1
// countNested(string: "[[][]]") == 3
// countNested(string: "[[]][[") == 2
func countNested(string: String) -> Int {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
continue
}
stack.pop()
count += 1
}
}
return count
}
// 3. Create a function that takes a string as input which contains only square brackets.
// The function should return the number of valid subsequences of brackets.
// countNested(string: "[[]]") == 2
// countNested(string: "[]]]]]]][[[[[]") == 0
// countNested(string: "[][]") == 0
// countNested(string: "[]") == 1
// countNested(string: "[[][]]") == 3
// countNested(string: "[[]][[") == 2
func countNested(string: String) -> Int {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
continue
}
stack.pop()
count += 1
}
}
return count
}
// 4. Create a function that takes a string as input which contains only square brackets.
// The function should return the number of valid subsequences of brackets.
// countNested(string: "[[]]") == 2
// countNested(string: "[]]]]]]][[[[[]") == 0
// countNested(string: "[][]") == 0
// countNested(string: "[]") == 1
// countNested(string: "[[][]]") == 3
// countNested(string: "[[]][[") == 2
func countNested(string: String) -> Int {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
continue
}
stack.pop()
count += 1
}
}
return count
}
// 5. Create a function that takes a string as input which contains only square brackets.
// The function should return the number of valid subsequences of brackets.
// countNested(string: "[[]]") == 2
// countNested(string: "[]]]]]]][[[[[]") == 0
// countNested(string: "[][]") == 0
// countNested(string: "[]") == 1
// countNested(string: "[[][]]") == 3
// countNested(string: "[[]][[") == 2
func countNested(string: String) -> Int {
var stack = [Character]()
var count = 0
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
continue
}
stack.pop()
count
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty {
return false
}
stack.pop()
}
}
return stack.isEmpty
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Vowels are the letters 'a', 'e', 'i', 'o', and 'u'.
// countVowels("Hello, world!") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels("AaEeIiOoUu") == 10
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 2. Write a function that takes a string as input and returns the number of words in the string.
// A word is defined as a sequence of non-whitespace characters surrounded by whitespace or the beginning or end of the string.
// countWords("Hello, world!") == 2
// countWords("Hello world!") == 2
// countWords("Hello, world") == 2
// countWords("Hello, world! ") == 2
// countWords("") == 0
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! ") == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
// countWords("Hello, world! " == 2
stack.pop() // value of type '[Character]' has no member 'pop'
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
return string.split(by: " ").count
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [Character]()
for char in string {
if char == "[" {
stack.append(char)
} else if char == "]" {
if stack.isEmpty() {
return false
}
stack.pop()
}
}
return stack.isEmpty()
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the number of vowels in the string.
// The vowels are 'a', 'e', 'i', 'o', 'u'.
// countVowels(string: "Hello world") == 3
// countVowels(string: "How are you?") == 5
// countVowels(string: "") == 0
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the number of words in the string.
// The words are separated by spaces.
// countWords(string: "Hello world") == 2
// countWords(string: "How are you?") == 3
// countWords(string: "") == 0
func countWords(string: String) -> Int {
return string.split(by: " ").count
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the number of vowels in the string.
// The vowels are 'a', 'e', 'i', 'o', 'u'.
// countVowels(string: "Hello world") == 3
// countVowels(string: "How are you?") == 5
// countVowels(string: "") == 0
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the number of words in the string.
// The words are separated by spaces.
// countWords(string: "Hello world") == 2
// countWords(string: "How are you?") == 3
// countWords(string: "") == 0
func countWords(string: String) -> Int {
return string.split(by: " ").count
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the number of words in the string.
// The words are separated by spaces.
// countWords(string: "Hello world") == 2
// countWords(string: "How are you?") == 3
// countWords(string: "") == 0
func countWords(string: String) -> Int {
return string.split(by: " ").count
}
// ---------------------------------------------------------------------------------------------
if stack.isEmpty() { // cannot call value of non-function type 'Bool'
stack.pop() // value of type '[Character]' has no member 'pop'
return stack.isEmpty() // cannot call value of non-function type 'Bool'
return string.split(by: " ").count // no exact matches in call to instance method 'split'
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
func swapCase(s: String) -> String {
var result = ""
for c in s {
if c.isUpper {
result += c.lower
} else {
result += c.upper
}
}
return result
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
// 2.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces,
// and leading/trailing spaces.
// For example:
// "Example Input" == "iNPUT eXAMPLE"
// " Example Input " == " INPUT eXAMPLE "
// " Example Input " == " iNPUT eXAMPLE "
// "Example Input" == "iNPUT eXAMPLE"
// "" == ""
func swapCase(s: String) -> String {
var result = ""
for c in s {
if c.isUpper {
result += c.lower
} else {
result += c.upper
}
}
return result
}
// 3.
// Given an array of numbers, return the sum of all of the positives ones.
// Example:
// [1,-4,7,12] => 1 + 7 + 12 = 20
// [1,2,3,4,5,6] => 1 + 2 + 3 + 4 + 5 + 6 = 21
// [1,2,3,4,5,-6,-7,8,9,10] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 41
// [1,2,3,4,5,-6,-7,8,9,-10] => 1 + 2 + 3 + 4 + 5 + 8 + 9 = 30
// [1,2,3,4,5,-6,-7,8,9,10,-11] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 42
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 45
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 48
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13,-14] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 51
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13,-14,-15] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 54
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13,-14,-15,-16] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 57
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13,-14,-15,-16,-17] => 1 + 2 + 3 + 4 + 5 + 8 + 9 + 10 = 60
// [1,2,3,4,5,-6,-7,8,9,10,-11,-12,-13,-14,-15,-16,-17,-18] => 1 + 2 +
if c.isUpper { // value of type 'Character' has no member 'isUpper'
result += c.lower // value of type 'Character' has no member 'lower'
result += c.upper // value of type 'Character' has no member 'upper'
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
func vowelCount(s: String) -> Int {
return s.count(for: .vowel)
}
func wordCount(s: String) -> Int {
return s.split(.whitespace).count
}
func consonantCount(s: String) -> Int {
return s.count(for: .consonant)
}
func uppercaseCount(s: String) -> Int {
return s.count(for: .uppercaseLetter)
}
func lowercaseCount(s: String) -> Int {
return s.count(for: .lowercaseLetter)
}
func digitCount(s: String) -> Int {
return s.count(for: .digit)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
// 2. Write a function that takes a string and returns the number of vowels in the string.
// You should ignore case.
// Examples:
// vowelCount("Hello") == 2
// vowelCount("Why do you ask?") == 4
// vowelCount("Why?") == 0
// vowelCount("C is cool") == 2
func vowelCount(s: String) -> Int {
return s.count(for: .vowel)
}
// 3. Write a function that takes a string and returns the number of words in the string.
// You should ignore case.
// Examples:
// wordCount("Hello") == 1
// wordCount("Why do you ask?") == 2
// wordCount("Why?") == 0
// wordCount("C is cool") == 2
func wordCount(s: String) -> Int {
return s.split(.whitespace).count
}
// 4. Write a function that takes a string and returns the number of consonants in the string.
// You should ignore case.
// Examples:
// consonantCount("Hello") == 3
// consonantCount("Why do you ask?") == 5
// consonantCount("Why?") == 0
// consonantCount("C is cool") == 4
func consonantCount(s: String) -> Int {
return s.count(for: .consonant)
}
// 5. Write a function that takes a string and returns the number of uppercase letters in the string.
// You should ignore case.
// Examples:
// uppercaseCount("Hello") == 1
// uppercaseCount("Why do you ask?") == 1
// uppercaseCount("Why?") == 0
// uppercaseCount("C is cool") == 0
func uppercaseCount(s: String) -> Int {
return s.count(for: .uppercaseLetter)
}
// 6. Write a function that takes a string and returns the number of lowercase letters in the string.
// You should ignore case.
// Examples:
// lowercaseCount("Hello") == 5
// lowercaseCount("Why do you ask?") == 5
// lowercaseCount("Why?") == 2
// lowercaseCount("C is cool") == 3
func lowercaseCount(s: String) -> Int {
return s.count(for: .lowercaseLetter)
}
// 7. Write a function that takes a string and returns the number of digits in the string.
// Examples:
// digitCount("Hello") == 0
// digitCount("Why do you ask?") == 0
// digitCount("Why?") == 0
// digitCount("C is cool") == 1
// digitCount("12345") == 5
func digitCount(s: String) -> Int {
return s.count(for: .digit)
}
// 8. Write a function that takes a string and returns the number of words in the string.
// You should ignore case.
// Examples:
// wordCount("Hello") == 1
// wordCount("Why do you ask?") == 2
// wordCount("Why?") == 0
// wordCount("C is cool") == 2
// wordCount("12345") == 1
func wordCount(s: String) -> Int {
return s.split(.whitespace).count
}
// 9. Write a function that takes a string and returns the number of consonants in the string.
// You should ignore case.
// Examples:
// consonantCount("Hello") == 3
// consonantCount("Why do you ask?") == 5
// consonantCount("Why?") == 0
// consonantCount("C is cool") == 4
// consonantCount("12
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // value of type 'Double' has no member 'ceil'
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // expected expression path in Swift key path
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // missing argument for parameter #2 in call
return s.count(for: .vowel) // cannot call value of non-function type 'Int'
return s.count(for: .vowel) // cannot infer contextual base in reference to member 'vowel'
return s.split(.whitespace).count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return s.split(.whitespace).count // no exact matches in call to instance method 'split'
return s.count(for: .consonant) // cannot infer contextual base in reference to member 'consonant'
return s.count(for: .consonant) // cannot call value of non-function type 'Int'
return s.count(for: .uppercaseLetter) // cannot call value of non-function type 'Int'
return s.count(for: .uppercaseLetter) // cannot infer contextual base in reference to member 'uppercaseLetter'
return s.count(for: .lowercaseLetter) // cannot call value of non-function type 'Int'
return s.count(for: .lowercaseLetter) // cannot infer contextual base in reference to member 'lowercaseLetter'
return s.count(for: .digit) // cannot call value of non-function type 'Int'
return s.count(for: .digit) // cannot infer contextual base in reference to member 'digit'
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // expected expression path in Swift key path
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // missing argument for parameter #2 in call
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // value of type 'Double' has no member 'ceil'
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // expected expression path in Swift key path
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // missing argument for parameter #2 in call
return lst.map { $0.ceil() }.map { $0 * $0 }.reduce(0, \+) // value of type 'Double' has no member 'ceil'
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
func reverseString(str: String) -> String {
return String(str.reversed())
}
func countVowels(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func reverseLetters(str: String) -> String {
var newStr = ""
for char in str {
newStr = char + newStr
}
return newStr
}
func isPalindrome(str: String) -> Bool {
var newStr = ""
for char in str {
if char.isLetter {
newStr += char
}
}
newStr = newStr.toLowerCase()
return newStr == newStr.reversed()
}
func countLetter(str: String) -> Int {
var count = 0
for char in str {
if char == "a" {
count += 1
}
}
return count
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
// 14. Write a function that takes a string as a parameter and
// returns a new string that is the reverse of the original.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Howdy") == "ydwoH"
// reverseString("Greetings from Earth") == "htraE from snirtseG"
func reverseString(str: String) -> String {
return String(str.reversed())
}
// 15. Write a function that takes a string as a parameter and
// returns the number of vowels in the string.
// You should ignore case.
// Examples:
// countVowels("yummy") == 3
// countVowels("yummy is my food") == 5
// countVowels("yummy is my food") == 5
func countVowels(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 16. Write a function that takes a string as a parameter and
// returns a new string that is the same as the original
// except that all letters have been swapped around.
// Examples:
// reverseLetters("hello") == "olleh"
// reverseLetters("Howdy") == "ydwoH"
// reverseLetters("Greetings from Earth") == "htraE from snirtseG"
func reverseLetters(str: String) -> String {
var newStr = ""
for char in str {
newStr = char + newStr
}
return newStr
}
// 17. Write a function that takes a string as a parameter and
// returns true if the string is a palindrome, and false otherwise.
// A palindrome is a word that is spelled the same forwards and backwards.
// Examples:
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
// isPalindrome("A man, a plan, a canal: Panama") == true
// isPalindrome("A Toyota's a Toyota") == true
// isPalindrome("A Toyota's a Toyota!") == false
func isPalindrome(str: String) -> Bool {
var newStr = ""
for char in str {
if char.isLetter {
newStr += char
}
}
newStr = newStr.toLowerCase()
return newStr == newStr.reversed()
}
// 18. Write a function that takes a string as a parameter and
// returns the number of times the letter "a" appears in the string.
// Examples:
// countLetter("apple") == 1
// countLetter("banana") == 3
// countLetter("orange") == 1
// countLetter("kiwi") == 0
// countLetter("apple") == 1
// countLetter("banana") == 3
// countLetter("orange") == 1
// countLetter("kiwi") == 0
func countLetter(str: String) -> Int {
var count = 0
for char in str {
if char == "a" {
count += 1
}
}
return count
}
// 19. Write a function that takes a string as a parameter and
// returns true if the string is a palindrome, and false otherwise.
// A palindrome is a word that is spelled the same forwards and backwards.
// Examples:
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
// isPalindrome("A man, a plan, a canal: Panama") == true
// isPalindrome("A Toyota's a Toyota") == true
// isPalindrome("
newStr = char + newStr // cannot convert value of type 'Character' to expected argument type 'String'
newStr += char // cannot convert value of type 'Character' to expected argument type 'String'
newStr = newStr.toLowerCase() // value of type 'String' has no member 'toLowerCase'
return newStr == newStr.reversed() // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * num))
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
func vowelCount(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * i))
}
return sum
}
// 2.
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Examples:
// vowelCount("abracadabra") == 5
// vowelCount("pear tree") == 5
// vowelCount("o a kak ushakov lil vo kashu kakao") == 12
// vowelCount("do geese see God?") == 5
// vowelCount("suppiiiccceess") == 7
// vowelCount("") == 0
func vowelCount(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 3.
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Examples:
// vowelCount("abracadabra") == 5
// vowelCount("pear tree") == 5
// vowelCount("o a kak ushakov lil vo kashu kakao") == 12
// vowelCount("do geese see God?") == 5
// vowelCount("suppiiiccceess") == 7
// vowelCount("") == 0
func vowelCount(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 4.
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Examples:
// vowelCount("abracadabra") == 5
// vowelCount("pear tree") == 5
// vowelCount("o a kak ushakov lil vo kashu kakao") == 12
// vowelCount("do geese see God?") == 5
// vowelCount("suppiiiccceess") == 7
// vowelCount("") == 0
func vowelCount(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 5.
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// Examples:
// vowelCount("abracadabra") == 5
// vowelCount("pear tree") == 5
// vowelCount("o a kak ushakov lil vo kashu kakao") == 12
// vowelCount("do geese see God?") == 5
// vowelCount("suppiiiccceess") == 7
// vowelCount("") == 0
func vowelCount(str: String) -> Int {
var count = 0
for char in str {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 6.
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// The vowel letters are
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!.isLetter() && !txt.contains(" ")
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!.isLetter() && !txt.contains(" ")
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
return txt.last!.isLetter() && !txt.contains(" ") // cannot call value of non-function type 'Bool'
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
let lastCharIsALetter = lastChar.isLetter
let lastCharIsALetterAndNotALetterPartOfAWord = lastCharIsALetter && !lastChar.isPartOfWord
return lastCharIsALetterAndNotALetterPartOfAWord
}
func sortByVowels(txt: String) -> [String] {
if txt.isEmpty {
return []
}
let vowels = "aeiou"
let vowelsCount = [0, 0, 0, 0, 0]
for char in txt {
if char.isVowel {
vowelsCount[char.toLowercaseString().firstIndex(of: vowels)!] += 1
}
}
let sortedVowelsCount = vowelsCount.sorted()
let sortedVowels = sortedVowelsCount.map { vowelsCount in
let vowels = "aeiou"
let vowelsCount = [0, 0, 0, 0, 0]
for char in txt {
if char.isVowel {
vowelsCount[char.toLowercaseString().firstIndex(of: vowels)!] += 1
}
}
vowelsCount.sorted()
}
return sortedVowels
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
let lastCharIsALetter = lastChar.isLetter
let lastCharIsALetterAndNotALetterPartOfAWord = lastCharIsALetter && !lastChar.isPartOfWord
return lastCharIsALetterAndNotALetterPartOfAWord
}
// ----------------------------------------------------------------------------------------------------------------------
// Exercise 10
// Create a function that takes a string as an argument and returns a list of strings, sorted by the number of vowels they contain.
// Note: "y" is not considered a vowel.
// Examples:
// sortByVowels("hello") == ["hello"]
// sortByVowels("codewars") == ["codewars"]
// sortByVowels("goodbye") == ["goodbye"]
// sortByVowels("aa") == ["aa"]
// sortByVowels("u") == []
// sortByVowels("") == []
func sortByVowels(txt: String) -> [String] {
if txt.isEmpty {
return []
}
let vowels = "aeiou"
let vowelsCount = [0, 0, 0, 0, 0]
for char in txt {
if char.isVowel {
vowelsCount[char.toLowercaseString().firstIndex(of: vowels)!] += 1
}
}
let sortedVowelsCount = vowelsCount.sorted()
let sortedVowels = sortedVowelsCount.map { vowelsCount in
let vowels = "aeiou"
let vowelsCount = [0, 0, 0, 0, 0]
for char in txt {
if char.isVowel {
vowelsCount[char.toLowercaseString().firstIndex(of: vowels)!] += 1
}
}
vowelsCount.sorted()
}
return sortedVowels
}
// ----------------------------------------------------------------------------------------------------------------------
// Exercise 11
// Create a function that takes a string as an argument and returns a list of strings, sorted by the number of upper case letters they contain.
// Note: "upper" is a group of uppercase letters.
// Examples:
// sortByUpperCase("Codewars") == ["Codewars"]
// sortByUpperCase("Codewars, The best site on the internet") == ["Codewars", "The"]
// sortByUpperCase("Codewars, codewars, codewars, codewars") == ["Codewars", "Codewars", "Codewars", "Codewars"]
// sortByUpperCase("I love to code") == ["I", "love", "to", "code"]
// sortByUpperCase("") == []
func sortByUpperCase(txt: String) -> [String] {
if txt.isEmpty {
return []
}
let upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let upperCaseLettersCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
let lastCharIsALetterAndNotALetterPartOfAWord = lastCharIsALetter && !lastChar.isPartOfWord // value of type 'String.Element' (aka 'Character') has no member 'isPartOfWord'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
vowelsCount[char.toLowercaseString().firstIndex(of: vowels)!] += 1 // value of type 'Character' has no member 'toLowercaseString'
if char.isVowel { // value of type 'Character' has no member 'isVowel'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
return isLetter(char: lastChar) && !isWord(char: lastChar)
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
return isLetter(char: lastChar) && !isWord(char: lastChar)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------
return isLetter(char: lastChar) && !isWord(char: lastChar) // cannot find 'isLetter' in scope
return isLetter(char: lastChar) && !isWord(char: lastChar) // cannot find 'isWord' in scope
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter()
let lastCharacterIsALetterOrSpace = lastCharacterIsALetter || lastCharacter == " "
let lastCharacterIsALetterOrSpaceOrEmpty = lastCharacterIsALetterOrSpace || lastCharacter == ""
return lastCharacterIsALetterOrSpaceOrEmpty
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter()
let lastCharacterIsALetterOrSpace = lastCharacterIsALetter || lastCharacter == " "
let lastCharacterIsALetterOrSpaceOrEmpty = lastCharacterIsALetterOrSpace || lastCharacter == ""
return lastCharacterIsALetterOrSpaceOrEmpty
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let lastCharacterIsALetter = lastCharacter.isLetter() // cannot call value of non-function type 'Bool'
let lastCharacterIsALetterOrSpaceOrEmpty = lastCharacterIsALetterOrSpace || lastCharacter == "" // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
let lastCharIsALetter = lastChar.isLetter()
let lastCharIsALetterAndIsNotALetter = lastCharIsALetter && !lastChar.isPartOfWord()
return lastCharIsALetterAndIsNotALetter
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastChar = txt.last!
let lastCharIsALetter = lastChar.isLetter()
let lastCharIsALetterAndIsNotALetter = lastCharIsALetter && !lastChar.isPartOfWord()
return lastCharIsALetterAndIsNotALetter
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
let lastCharIsALetter = lastChar.isLetter() // cannot call value of non-function type 'Bool'
let lastCharIsALetterAndIsNotALetter = lastCharIsALetter && !lastChar.isPartOfWord() // value of type 'String.Element' (aka 'Character') has no member 'isPartOfWord'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
return isLetter(lastChar) && !isWord(txt)
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
return isLetter(lastChar) && !isWord(txt)
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return isLetter(lastChar) && !isWord(txt) // cannot find 'isWord' in scope
return isLetter(lastChar) && !isWord(txt) // cannot find 'isLetter' in scope
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let isALetter = lastCharacter.isLetter()
let isALineBreak = lastCharacter.isLineBreak()
return isALetter && !isALineBreak
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let isALetter = lastCharacter.isLetter()
let isALineBreak = lastCharacter.isLineBreak()
return isALetter && !isALineBreak
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
let isALetter = lastCharacter.isLetter() // cannot call value of non-function type 'Bool'
let isALineBreak = lastCharacter.isLineBreak() // value of type 'String.Element' (aka 'Character') has no member 'isLineBreak'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter()
let lastCharacterIsALetterAndIsNotALetterPartOfAWord = lastCharacterIsALetter && !lastCharacter.isPartOfAWord()
return lastCharacterIsALetterAndIsNotALetterPartOfAWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastCharacter = txt.last!
let lastCharacterIsALetter = lastCharacter.isLetter()
let lastCharacterIsALetterAndIsNotALetterPartOfAWord = lastCharacterIsALetter && !lastCharacter.isPartOfAWord()
return lastCharacterIsALetterAndIsNotALetterPartOfAWord
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let lastCharacterIsALetter = lastCharacter.isLetter() // cannot call value of non-function type 'Bool'
let lastCharacterIsALetterAndIsNotALetterPartOfAWord = lastCharacterIsALetter && !lastCharacter.isPartOfAWord() // value of type 'String.Element' (aka 'Character') has no member 'isPartOfAWord'
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!.isLetter()
}
func sortByVowels(txt: String) -> [String] {
return txt.split(separator: " ").map {
$0.countVowels()
}.sorted().map {
$0.first!
}
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
return txt.last!.isLetter()
}
// -----------------------------------------------------------------------------
// 14. Create a function that takes a string as an argument and returns a list
// of strings containing the words from the string, sorted by the number of
// vowels each word has.
// Examples:
// sortByVowels("Hello") == ["Hello"]
// sortByVowels("MindControl") == ["Control", "Mind"]
// sortByVowels("YouAreBeautiful") == ["Beautiful", "You"]
func sortByVowels(txt: String) -> [String] {
return txt.split(separator: " ").map {
$0.countVowels()
}.sorted().map {
$0.first!
}
}
// -----------------------------------------------------------------------------
// 15. Create a function that takes a string as an argument and returns a list
// of strings containing the words from the string, sorted by the number of
// vowels each word has.
// Examples:
// sortByVowels("Hello") == ["Hello"]
// sortByVowels("MindControl") == ["Control", "Mind"]
// sortByVowels("YouAreBeautiful") == ["Beautiful", "You"]
func sortByVowels(txt: String) -> [String] {
return txt.split(separator: " ").map {
$0.countVowels()
}.sorted().map {
$0.first!
}
}
// -----------------------------------------------------------------------------
// 16. Create a function that takes a string as an argument and returns a list
// of strings containing the words from the string, sorted by the number of
// vowels each word has.
// Examples:
// sortByVowels("Hello") == ["Hello"]
// sortByVowels("MindControl") == ["Control", "Mind"]
// sortByVowels("YouAreBeautiful") == ["Beautiful", "You"]
func sortByVowels(txt: String) -> [String] {
return txt.split(separator: " ").map {
$0.countVowels()
}.sorted().map {
$0.first!
}
}
// -----------------------------------------------------------------------------
// 17. Create a function that takes a string as an argument and returns a list
// of strings containing the words from the string, sorted by the number of
// vowels each word has.
// Examples:
// sortByVowels("Hello") == ["Hello"]
// sortByVowels("MindControl") == ["Control", "Mind"]
// sortByVowels("YouAreBeautiful") == ["Beautiful", "You"]
func sortByVowels(txt: String) -> [String] {
return txt.split(separator: " ").map {
$0.countVowels()
}.sorted().map {
$0.first!
}
}
// -----------------------------------------------------------------------------
// 18. Create a function that takes a string as an argument and returns a list
// of strings containing the words from the string, sorted by the number of
// vowels each word has.
// Examples:
// sortByVowels("Hello") == ["Hello"]
// sortByVowels("MindControl") == ["Control", "Mind"]
// sortByVowels("YouAreBeautiful") == ["Beautiful", "You"]
func sortByVowels(txt: String) -> [
return txt.last!.isLetter() // cannot call value of non-function type 'Bool'
$0.countVowels() // reference to member 'countVowels' cannot be resolved without a contextual type
}.sorted().map { // cannot infer type of closure parameter '$0' without a type annotation
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
if lastCharacter.isLetter {
return true
}
return false
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
if txt.isEmpty {
return false
}
let lastCharacter = txt.last!
if lastCharacter.isLetter {
return true
}
return false
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 13. Write a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
result = i
break
}
i += 1
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var i = 0
while i < arr.count {
if arr[i] > arr[i + 1] {
result = i
break
}
i += 1
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i - 1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i - 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i-1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i-1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i - 1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i - 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i + 1] {
result = i
}
}
return result
}
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i + 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes an array of integers and returns the sum of
// all the integers in the array.
// Examples:
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
func sum(arr: [Int]) -> Int {
return arr.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
//
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i - 1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i - 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Given an array of integers, find the index of the element that
// has the greatest distance from every other element.
// Examples:
// maxDistance([1, 2, 3, 2, 1]) == 3
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 6
// maxDistance([1, 2, 3, 2, 1, 4, 5, 3, 2, 3, 2, 1, 2, 3,
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i + 1] {
result = i
}
}
return result
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] < arr[i + 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Fatal error: Index out of range
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i - 1] {
result = i
}
}
return result
}
func sumIntegers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element })
}
func sumSquares(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element })
}
func sumCubes(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element })
}
func sumFourthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element })
}
func sumFifthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element * element })
}
func sumSixthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element * element * element })
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var result = -1
for i in 0..<arr.count {
if arr[i] > arr[i - 1] {
result = i
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an array of integers and returns the sum of
// the integers. The integers can be positive, negative, or both.
// Examples:
// sumIntegers(arr: [1, 2, 3]) == 6
// sumIntegers(arr: [1, 2, -3]) == 0
func sumIntegers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element })
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes an array of integers and returns the sum of
// the squares of the integers. The integers can be positive, negative, or both.
// Examples:
// sumSquares(arr: [1, 2, 3]) == 14
// sumSquares(arr: [1, 2, -3]) == 5
func sumSquares(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element })
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an array of integers and returns the sum of
// the cubes of the integers. The integers can be positive, negative, or both.
// Examples:
// sumCubes(arr: [1, 2, 3]) == 14
// sumCubes(arr: [1, 2, -3]) == 27
func sumCubes(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element })
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes an array of integers and returns the sum of
// the fourth powers of the integers. The integers can be positive, negative,
// or both.
// Examples:
// sumFourthPowers(arr: [1, 2, 3]) == 14
// sumFourthPowers(arr: [1, 2, -3]) == 8
func sumFourthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element })
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes an array of integers and returns the sum of
// the fifth powers of the integers. The integers can be positive, negative,
// or both.
// Examples:
// sumFifthPowers(arr: [1, 2, 3]) == 14
// sumFifthPowers(arr: [1, 2, -3]) == 125
func sumFifthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element * element })
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes an array of integers and returns the sum of
// the sixth powers of the integers. The integers can be positive, negative,
// or both.
// Examples:
// sumSixthPowers(arr: [1, 2, 3]) == 14
// sumSixthPowers(arr: [1, 2, -3]) == 123
func sumSixthPowers(arr: [Int]) -> Int {
return arr.reduce(0, \(sum, element) { sum + element * element * element * element * element * element })
}
// ---------------
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var a = nil
var b = nil
for i in lst {
if i < 0 {
if a == nil || i > a {
a = i
}
} else {
if b == nil || i < b {
b = i
}
}
}
return (a, b)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var a = nil
var b = nil
for i in lst {
if i < 0 {
if a == nil || i > a {
a = i
}
} else {
if b == nil || i < b {
b = i
}
}
}
return (a, b)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------
var a = nil // 'nil' requires a contextual type
var b = nil // 'nil' requires a contextual type
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative {
negative = i
}
} else {
if positive == nil || i < positive {
positive = i
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative {
negative = i
}
} else {
if positive == nil || i < positive {
positive = i
}
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
var negative = nil // 'nil' requires a contextual type
var positive = nil // 'nil' requires a contextual type
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let sorted = lst.sorted()
let negative = sorted.first(where: { $0 < 0 })
let positive = sorted.last(where: { $0 > 0 })
return (negative, positive)
}
func reverseLetters(s: String) -> String {
return String(s.reversed())
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let sorted = lst.sorted()
let negative = sorted.first(where: { $0 < 0 })
let positive = sorted.last(where: { $0 > 0 })
return (negative, positive)
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the string
// with all the letters reversed.
// Examples:
// reverseLetters("hello") == "olleh"
// reverseLetters("") == ""
// reverseLetters("a") == "a"
func reverseLetters(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the string
// with all the letters replaced by their ASCII values.
// Examples:
// asciiValue("hello") == "104101121111111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011111011
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.count == 0 {
return (nil, nil)
}
var negative = 0
var positive = 0
for i in lst {
if i < 0 {
negative = i
} else {
positive = i
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.count == 0 {
return (nil, nil)
}
var negative = 0
var positive = 0
for i in lst {
if i < 0 {
negative = i
} else {
positive = i
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else if i < negative! {
negative = i
}
} else if i > 0 {
if positive == nil {
positive = i
} else if i > positive! {
positive = i
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else if i < negative! {
negative = i
}
} else if i > 0 {
if positive == nil {
positive = i
} else if i > positive! {
positive = i
}
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var a = nil
var b = nil
for i in lst {
if i < 0 {
if a == nil || i > a {
a = i
}
} else if i > 0 {
if b == nil || i < b {
b = i
}
}
}
return (a, b)
}
func countVowels(s: String) -> Int {
var count = 0
for i in s {
switch i {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
count += 1
default:
break
}
}
return count
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var a = nil
var b = nil
for i in lst {
if i < 0 {
if a == nil || i > a {
a = i
}
} else if i > 0 {
if b == nil || i < b {
b = i
}
}
}
return (a, b)
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the number of
// vowels in the string.
// Examples:
// countVowels("Hello world") == 3
// countVowels("") == 0
// countVowels("aeiou") == 5
// countVowels("AEIOU") == 5
// countVowels("bcdfghjklmnpqrstvwxyz") == 0
func countVowels(s: String) -> Int {
var count = 0
for i in s {
switch i {
case "a", "e", "i", "o", "u", "A", "E", "I", "O", "U":
count += 1
default:
break
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the number of
// words in the string.
// Examples:
// countWords("Hello world") == 2
// countWords("") == 0
// countWords("Hello world!") == 2
// countWords("Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!") == 2
// countWords("Hello world! Hello world! Hello world! Hello world
var a = nil // 'nil' requires a contextual type
var b = nil // 'nil' requires a contextual type
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else if i > negative {
negative = i
}
} else if i > 0 {
if positive == nil {
positive = i
} else if i < positive {
positive = i
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else if i > negative {
negative = i
}
} else if i > 0 {
if positive == nil {
positive = i
} else if i < positive {
positive = i
}
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// 2. Write a function that returns the sum of all the numbers in an array.
// Examples:
// sum([1, 2, 3]) == 6
// sum([1, 2, 3, 4]) == 10
// sum([1, 2, 3, 4, 5]) == 15
// sum([1, 2, 3, 4, 5, 6]) == 21
// sum([1, 2, 3, 4, 5, 6, 7]) == 28
// sum([1, 2, 3, 4, 5, 6, 7, 8]) == 36
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 45
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 66
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == 78
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == 91
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == 105
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 121
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == 137
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == 155
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == 172
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == 190
// sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == 208
// sum([1, 2, 3, 4, 5, 6
var negative = nil // 'nil' requires a contextual type
var positive = nil // 'nil' requires a contextual type
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let sorted = lst.sorted()
let negative = sorted.filter { $0 < 0 }
let positive = sorted.filter { $0 > 0 }
return (negative.last, positive.first)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let sorted = lst.sorted()
let negative = sorted.filter { $0 < 0 }
let positive = sorted.filter { $0 > 0 }
return (negative.last, positive.first)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as an argument and returns a tuple
// (a, b), where 'a' is the number of uppercase letters and 'b' is the number
// of lowercase letters in the string.
// Examples:
// countUppercaseLowercase("Hello World") == (4, 11)
// countUppercaseLowercase("HELLO WORLD") == (0, 11)
// countUppercaseLowercase("hello world") == (1, 11)
// countUppercaseLowercase("") == (0, 0)
// countUppercaseLowercase(" ") == (0, 0)
// countUppercaseLowercase("12345") == (0, 5)
// countUppercaseLowercase("abcdefg") == (7, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZ") == (0, 0)
// countUppercaseLowercase("abcdefghijklmnopqrstuvwxyz") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyz") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()") == (0, 0)
// countUppercaseLowercase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyz1234567890!@#$
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.count == 0 {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative {
negative = i
}
} else {
if positive == nil || i < positive {
positive = i
}
}
}
return (negative, positive)
}
func countUppercaseAndLowercase(s: String) -> (Int, Int) {
var uppercase = 0
var lowercase = 0
for c in s {
if c.isUpper {
uppercase += 1
} else {
lowercase += 1
}
}
return (uppercase, lowercase)
}
func countVowelsAndConsonants(s: String) -> (Int, Int) {
var vowels = 0
var consonants = 0
for c in s {
if c.isVowel {
vowels += 1
} else {
consonants += 1
}
}
return (vowels, consonants)
}
func countUppercaseAndLowercase(s: String) -> (Int?, Int?) {
var uppercase = nil
var lowercase = nil
for c in s {
if c.isUpper {
if uppercase == nil || c > uppercase {
uppercase = c
}
} else {
if lowercase == nil || c < lowercase {
lowercase = c
}
}
}
return (uppercase, lowercase)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.count == 0 {
return (nil, nil)
}
var negative = nil
var positive = nil
for i in lst {
if i < 0 {
if negative == nil || i > negative {
negative = i
}
} else {
if positive == nil || i < positive {
positive = i
}
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns a tuple (a, b),
// where 'a' is the number of uppercase letters, and 'b' is the number of lowercase letters.
// Examples:
// countUppercaseAndLowercase("Hello World") == (4, 7)
// countUppercaseAndLowercase("HELLO WORLD") == (0, 11)
// countUppercaseAndLowercase("12345") == (0, 0)
// countUppercaseAndLowercase("") == (0, 0)
func countUppercaseAndLowercase(s: String) -> (Int, Int) {
var uppercase = 0
var lowercase = 0
for c in s {
if c.isUpper {
uppercase += 1
} else {
lowercase += 1
}
}
return (uppercase, lowercase)
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns a tuple (a, b),
// where 'a' is the number of vowels ('a', 'e', 'i', 'o', 'u'), and 'b' is the number of consonants.
// Examples:
// countVowelsAndConsonants("Hello World") == (3, 7)
// countVowelsAndConsonants("HELLO WORLD") == (5, 5)
// countVowelsAndConsonants("12345") == (0, 0)
// countVowelsAndConsonants("") == (0, 0)
func countVowelsAndConsonants(s: String) -> (Int, Int) {
var vowels = 0
var consonants = 0
for c in s {
if c.isVowel {
vowels += 1
} else {
consonants += 1
}
}
return (vowels, consonants)
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns a tuple (a, b),
// where 'a' is the number of uppercase letters, and 'b' is the number of lowercase letters.
// If there is no uppercase or lowercase letters, return them as nil.
// Examples:
// countUppercaseAndLowercase("Hello World") == (4, 7)
// countUppercaseAndLowercase("HELLO WORLD") == (0, 11)
// countUppercaseAndLowercase("12345") == (0, 0)
// countUppercaseAndLowercase("") == (0, 0)
func countUppercaseAndLowercase(s: String) -> (Int?, Int?) {
var uppercase = nil
var lowercase = nil
for c in s {
if c.isUpper {
if uppercase == nil || c > uppercase {
uppercase = c
}
} else {
if lowercase == nil || c < lowercase {
lowercase = c
}
}
}
return (uppercase, lowercase)
}
// ------------------------------------------------------------------------
var negative = nil // 'nil' requires a contextual type
var positive = nil // 'nil' requires a contextual type
if c.isUpper { // value of type 'Character' has no member 'isUpper'
if c.isVowel { // value of type 'Character' has no member 'isVowel'
var uppercase = nil // 'nil' requires a contextual type
var lowercase = nil // 'nil' requires a contextual type
if c.isUpper { // value of type 'Character' has no member 'isUpper'
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else {
negative = min(i, negative!)
}
} else {
if positive == nil {
positive = i
} else {
positive = max(i, positive!)
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative: Int? = nil
var positive: Int? = nil
for i in lst {
if i < 0 {
if negative == nil {
negative = i
} else {
negative = min(i, negative!)
}
} else {
if positive == nil {
positive = i
} else {
positive = max(i, positive!)
}
}
}
return (negative, positive)
}
// -----------------------------------------------------------------------------
// 11. Write a function that returns the sum of the digits of a given number.
// Examples:
// sumDigits(10) == 1
// sumDigits(99) == 18
// sumDigits(-32) == 5
// sumDigits(54321) == 21
// sumDigits(0) == 0
// sumDigits(123456789) == 45
// sumDigits(9876543210) == 45
// sumDigits(12345678901234567890) == 45
// sumDigits(12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
// XCTAssertTrue failed
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .stringValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .stringValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
// Create a function that takes an integer and returns it as a string in
// Expanded Form. For example:
// expandedForm(12) == "10 + 2"
// expandedForm(42) == "40 + 2"
// expandedForm(70304) == "70000 + 300 + 4"
// Notes:
// 1. All numbers will be whole numbers greater than 0.
// 2. Do not pad your number with extra zeros.
// 3. Return the result as a string.
// 4. The expanded form must be correct for all numbers up to 9999.
// 5. There are no inner functions in this kata.
// 6. Expanded Form should not use the number's original format.
// 7. The numbers should be expanded left to right.
// 8. There are no inner functions in this kata.
// 9. Do not return 0 for numbers that are zero.
// 10. Expanded Form should not return anything.
// 11. Do not hard code "+" and spaces.
// 12. Do not return a string for numbers that have three digits or less.
// 13. Do not return anything for numbers that are already a string.
// 14. Do not convert the numbers to strings using string().
// 15. Do not convert the numbers to strings using string().
// 16. Do not use the number's original format.
// 17. Do not use the number's original format.
// 18. Do not use the number's original format.
// 19. Do not use the number's original format.
// 20. Do not use the number's original format.
// 21. Do not use the number's original format.
// 22. Do not use the number's original format.
// 23. Do not use the number's original format.
// 24. Do not use the number's original format.
// 25. Do not use the number's original format.
// 26. Do not use the number's original format.
// 27. Do not use the number's original format.
// 28. Do not use the number's original format.
// 29. Do not use the number's original format.
// 30. Do not use the number's original format.
// 31. Do not use the number's original format.
// 32. Do not use the number's original format.
// 33. Do not use the number's original format.
// 34. Do not use the number's original format.
// 35. Do not use the number's original format.
// 36. Do not use the number's original format.
//
return a > b ? .intValue(a) : .doubleValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : .stringValue(b) // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return a > Double(b) ? .stringValue(a) : .stringValue(b) // cannot convert value of type 'Double' to expected argument type 'String'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
func incOne(number: Int) -> Int {
return number + 1
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments the number by +1 and returns the result.
// Note: If the number is negative, just decrement it by -1.
// incOne(1) == 2
// incOne(0) == 1
// incOne(-1) == -2
func incOne(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number as an argument,
// increments
return a > b ? .intValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
// Create a function that takes a string and returns the first character that
// is not a space.
// If there are no non-space characters in the string, return nil.
// Notes:
// The string will always contain at least one character.
// Spaces do not count as non-space characters.
// There will always be at least one non-space character in the string.
// Examples:
// firstNonSpace("Hello World") == "H"
// firstNonSpace("H ello World") == "H"
// firstNonSpace(" Hello World") == "H"
// firstNonSpace("Hello World ") == "H"
// firstNonSpace("Hello World ") == "H"
// firstNonSpace("") == nil
// firstNonSpace(" ") == nil
// firstNonSpace(" ") == nil
// firstNonSpace("a b c") == "a"
// firstNonSpace(" a b c") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a"
// firstNonSpace(" a b c ") == "a
return a > b ? .intValue(a) : .doubleValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : .stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : .intValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : .stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : .intValue(b) // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : .doubleValue(b) // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
func repeat(text: String) -> String {
return text.map { $0 * 2 }.joined()
}
func nextValue(num: Int) -> Int {
return num + 1
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
// Create a function that takes a string and returns a string in which each character
// is repeated once.
// repeat("Hello") == "HHeelllloo"
// repeat("Good job!") == "GGoooodd jjoobbbeeccc!!"
// repeat("") == ""
func repeat(text: String) -> String {
return text.map { $0 * 2 }.joined()
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and returns the result.
// nextValue(0) == 1
// nextValue(90) == 91
// nextValue(-3) == -2
func nextValue(num: Int) -> Int {
return num + 1
}
// Create a function that takes a number as an argument, increments the number by
// +1 and
return a > b ? .intValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
func repeat(text: String) -> String { // keyword 'repeat' cannot be used as an identifier here
return text.map { $0 * 2 }.joined() // binary operator '*' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'Int'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
default:
return nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
default:
return nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
default:
return nil
}
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
default:
return nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
default:
return nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
default:
return nil
}
default:
return nil
}
}
// Create a function that takes a string and returns the first character that
// is not repeated.
// Notes:
// - If there is no non-repeated character, return nil.
// - If there is more than one non-repeated first character, return the first one encountered.
// - The given string will contain letters only.
// Examples:
// - compareOne("apple") == "p"
// - compareOne("banana") == "b"
// - compareOne("cacophony") == "f"
// - compareOne("edabit") == "a"
// - compareOne("haha") == "h"
// - compareOne("lollipop") == "p"
// - compareOne("") == nil
// - compareOne("c") == "c"
// - compareOne("hamburger") == "h"
// - compareOne("hippopotamus") == "h"
// - compareOne("perform") == "p"
// - compareOne("supercalifragilisticexpialidocious") == "s"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
// - compareOne("transgression") == "g"
return a > b ? .intValue(a) : .doubleValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : .stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : .intValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : .stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : .intValue(b) // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : .doubleValue(b) // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
func sumOfMultiples(number: Int) -> Int {
var sum = 0
for i in 1...number {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
func numberIncrementor(number: Int) -> Int {
return number + 1
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
// Create a function that takes an integer and returns the sum of all the
// multiples of 3 and 5 up to and including that integer.
// If there is no answer, return 0.
// Note: 15 is not a multiple of 3 or 5, so it does not count.
// sumOfMultiples(5) == 3
// sumOfMultiples(10) == 3 + 5 + 6 + 9 == 23
// sumOfMultiples(15) == 3 + 5 + 6 + 9 + 10 + 12 + 15 == 45
func sumOfMultiples(number: Int) -> Int {
var sum = 0
for i in 1...number {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// Create a function that takes a number as an argument, increments the number
// by +1 and returns the result.
// numberIncrementor(0) == 1
// numberIncrementor(9) == 10
// numberIncrementor(-3) == -2
func numberIncrementor(number: Int) -> Int {
return number + 1
}
// Create a function that takes a number (step) as an argument and returns the
// string representation of a step in a Hanoi sequence. The return value should
// be a string containing the number of disks, the start, and end positions
// (see examples below).
// Hanoi(0) == ""
// Hanoi(1) == "1: A to C"
// Hanoi(2) =>
// "2: A to B"
// "1: A to C"
// "2: B to A"
// "1: B to C"
// "2: A to B"
// "1: A to C"
// Hanoi(3) =>
// "3: A to B"
// "2: A to C"
// "1: B to C"
// "3: B to A"
// "2: B to C"
// "1: A to B"
// "2: A to C"
// "1: B to C"
// "3: A to B"
// "2: C to A"
// "1: C to B"
// "3: C to A"
// Hanoi(4) =>
// "4: A to B"
// "3: A to C"
// "2: A to B"
// "1: B to C"
// "4: B to A"
// "3: B to C"
return a > b ? .intValue(a) : .doubleValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : .stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : .intValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : .stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : .intValue(b) // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : .doubleValue(b) // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .intValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : .stringValue(b)
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : .intValue(b)
case .doubleValue(let b):
return a > b ? .doubleValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : .stringValue(b)
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : .intValue(b)
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : .doubleValue(b)
case .stringValue(let b):
return a > b ? .stringValue(a) : .stringValue(b)
}
}
return nil
}
// Create a function that takes a string and returns it as an integer.
// If the string is an integer, return the integer.
// If the string is a floating point number, return the integer part.
// If the string is a fraction, return the integer part of the number.
// If the string is a negative integer, return the integer part of the number.
// If the string is a positive integer, return the integer part of the number.
// If the string is a negative real number, return the integer part of the number.
// If the string is a positive real number, return the integer part of the number.
// If the string is a negative decimal number, return the integer part of the number.
// If the string is a positive decimal number, return the integer part of the number.
// If the string is a negative infinity, return "-Infinity".
// If the string is a positive infinity, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Infinity".
// If the string is a positive infinity fraction, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Infinity".
// If the string is a positive infinity fraction, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Infinity".
// If the string is a positive infinity fraction, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Infinity".
// If the string is a positive infinity fraction, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Infinity".
// If the string is a positive infinity fraction, return "Infinity".
// If the string is a negative decimal fraction, return the integer part of the number.
// If the string is a positive decimal fraction, return the integer part of the number.
// If the string is a negative infinity fraction, return "-Inf
return a > b ? .intValue(a) : .doubleValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : .stringValue(b) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : .intValue(b) // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : .stringValue(b) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : .intValue(b) // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : .doubleValue(b) // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
if a == b {
return nil
}
if a.isInt() && b.isInt() {
return a.intValue > b.intValue ? a : b
}
if a.isDouble() && b.isDouble() {
return a.doubleValue > b.doubleValue ? a : b
}
if a.isString() && b.isString() {
return a.stringValue > b.stringValue ? a : b
}
return nil
}
func intToString(n: Int?) -> String? {
if n == nil {
return nil
}
if n == 0 {
return "0"
}
if n < Int.min || n > Int.max {
return nil
}
return "\(n)"
}
func stringToInt(s: String) -> Int? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return Int(s.substring(1)) * -1
}
return Int(s)
}
func stringToDouble(s: String) -> Double? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return Double(s.substring(1)) * -1
}
return Double(s)
}
func stringToString(s: String) -> String? {
return s
}
func stringToAny(s: String) -> Any? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return s.substring(1)
}
return s
}
func anyToString(a: Any) -> String? {
if a == 0 {
return "0"
}
if a is Int {
return "\(a)"
}
if a is Double {
return "\(a)"
}
if a is String {
return a
}
return nil
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
if a == b {
return nil
}
if a.isInt() && b.isInt() {
return a.intValue > b.intValue ? a : b
}
if a.isDouble() && b.isDouble() {
return a.doubleValue > b.doubleValue ? a : b
}
if a.isString() && b.isString() {
return a.stringValue > b.stringValue ? a : b
}
return nil
}
// Create a function that takes an integer and returns it as a string in the
// form "123", "-123", "0", or nil if the integer is nil.
// Note: If the integer is zero, return "0".
// Note: If the integer is negative, the negative sign should be part of the string.
// Note: If the integer is greater than Int.max or less than Int.min, return nil.
func intToString(n: Int?) -> String? {
if n == nil {
return nil
}
if n == 0 {
return "0"
}
if n < Int.min || n > Int.max {
return nil
}
return "\(n)"
}
// Create a function that takes a string and returns a string that is
// formatted as a number.
// Note: If the number is negative, the negative sign should be part of the string.
// Note: If the number is zero, return "0".
// Note: If the number is greater than Int.max or less than Int.min, return nil.
func stringToInt(s: String) -> Int? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return Int(s.substring(1)) * -1
}
return Int(s)
}
// Create a function that takes a string and returns a string that is
// formatted as a number.
// Note: If the number is negative, the negative sign should be part of the string.
// Note: If the number is zero, return "0".
// Note: If the number is greater than Int.max or less than Int.min, return nil.
func stringToDouble(s: String) -> Double? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return Double(s.substring(1)) * -1
}
return Double(s)
}
// Create a function that takes a string and returns a string that is
// formatted as a number.
// Note: If the number is negative, the negative sign should be part of the string.
// Note: If the number is zero, return "0".
// Note: If the number is greater than Int.max or less than Int.min, return nil.
func stringToString(s: String) -> String? {
return s
}
// Create a function that takes a string and returns a string that is
// formatted as a number.
// Note: If the number is negative, the negative sign should be part of the string.
// Note: If the number is zero, return "0".
// Note: If the number is greater than Int.max or less than Int.min, return nil.
func stringToAny(s: String) -> Any? {
if s == "0" {
return 0
}
if s.startsWith("-") {
return s.substring(1)
}
return s
}
// Create a function that takes a string and returns a string that is
// formatted as a number.
// Note: If the number is negative, the negative sign should be part of the string.
// Note: If the number is zero, return "0".
// Note: If the number is greater than Int.max or less than Int.min, return nil.
func anyToString(a: Any) -> String? {
if a == 0 {
return "0"
}
if a is Int {
return "\(a)"
}
if a is Double {
return "\(a)"
}
if a is String {
return a
}
return nil
}
// Create a
if a.isInt() && b.isInt() { // value of type 'Value' has no member 'isInt'
if a.isInt() && b.isInt() { // value of type 'Value' has no member 'isInt'
return a.intValue > b.intValue ? a : b // enum case 'intValue' cannot be used as an instance member
return a.intValue > b.intValue ? a : b // enum case 'intValue' cannot be used as an instance member
return a.intValue > b.intValue ? a : b // type '(Int) -> Value' cannot conform to 'Comparable'
if a.isDouble() && b.isDouble() { // value of type 'Value' has no member 'isDouble'
if a.isDouble() && b.isDouble() { // value of type 'Value' has no member 'isDouble'
return a.doubleValue > b.doubleValue ? a : b // type '(Double) -> Value' cannot conform to 'Comparable'
return a.doubleValue > b.doubleValue ? a : b // enum case 'doubleValue' cannot be used as an instance member
return a.doubleValue > b.doubleValue ? a : b // enum case 'doubleValue' cannot be used as an instance member
if a.isString() && b.isString() { // value of type 'Value' has no member 'isString'
if a.isString() && b.isString() { // value of type 'Value' has no member 'isString'
return a.stringValue > b.stringValue ? a : b // enum case 'stringValue' cannot be used as an instance member
return a.stringValue > b.stringValue ? a : b // type '(String) -> Value' cannot conform to 'Comparable'
return a.stringValue > b.stringValue ? a : b // enum case 'stringValue' cannot be used as an instance member
if n < Int.min || n > Int.max { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if n < Int.min || n > Int.max { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return "\(n)" // string interpolation produces a debug description for an optional value; did you mean to make this explicit?
if s.startsWith("-") { // value of type 'String' has no member 'startsWith'
return Int(s.substring(1)) * -1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(s.substring(1)) * -1 // no exact matches in call to instance method 'substring'
if s.startsWith("-") { // value of type 'String' has no member 'startsWith'
return Double(s.substring(1)) * -1 // no exact matches in call to instance method 'substring'
return Double(s.substring(1)) * -1 // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
if s.startsWith("-") { // value of type 'String' has no member 'startsWith'
return s.substring(1) // no exact matches in call to instance method 'substring'
if a == 0 { // cannot convert value of type 'Any' to expected argument type 'Int'
return a // cannot convert return expression of type 'Any' to return type 'String?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
if a == b {
return nil
}
if a.type == b.type {
return a.type.type(a.value)
}
if a.type == .intValue {
return b.type.type(b.value)
}
if a.type == .doubleValue {
return b.type.type(b.value)
}
if a.type == .stringValue {
return b.type.type(b.value)
}
return nil
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
if a == b {
return nil
}
if a.type == b.type {
return a.type.type(a.value)
}
if a.type == .intValue {
return b.type.type(b.value)
}
if a.type == .doubleValue {
return b.type.type(b.value)
}
if a.type == .stringValue {
return b.type.type(b.value)
}
return nil
}
// Create a function that takes an integer and returns it as a string in the
// form "123", "-123", "0", or nil if the integer is nil.
// Note: If the integer is zero, return "0".
// Note: If the integer is positive, return a string with a "+" in front of it.
// Note: If the integer is negative, return a string with a "-" in front of it.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the integer is not an integer, return nil.
// Note: If the
if a.type == b.type { // value of type 'Value' has no member 'type'
if a.type == b.type { // value of type 'Value' has no member 'type'
return a.type.type(a.value) // value of type 'Value' has no member 'value'
return a.type.type(a.value) // value of type 'Value' has no member 'type'
if a.type == .intValue { // value of type 'Value' has no member 'type'
if a.type == .intValue { // cannot infer contextual base in reference to member 'intValue'
return b.type.type(b.value) // value of type 'Value' has no member 'value'
return b.type.type(b.value) // value of type 'Value' has no member 'type'
if a.type == .doubleValue { // cannot infer contextual base in reference to member 'doubleValue'
if a.type == .doubleValue { // value of type 'Value' has no member 'type'
return b.type.type(b.value) // value of type 'Value' has no member 'value'
return b.type.type(b.value) // value of type 'Value' has no member 'type'
if a.type == .stringValue { // cannot infer contextual base in reference to member 'stringValue'
if a.type == .stringValue { // value of type 'Value' has no member 'type'
return b.type.type(b.value) // value of type 'Value' has no member 'value'
return b.type.type(b.value) // value of type 'Value' has no member 'type'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
func doubleChar(str: String) -> String {
return String(str.map { $0 * 2 })
}
func nextValue(n: Int) -> Int {
return n + 1
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(let a):
switch b {
case .intValue(let b):
return a > b ? .intValue(a) : nil
case .doubleValue(let b):
return a > b ? .intValue(a) : nil
case .stringValue(let b):
return a > Int(b) ? .intValue(a) : nil
}
case .doubleValue(let a):
switch b {
case .intValue(let b):
return a > b ? .doubleValue(a) : nil
case .doubleValue(let b):
return a > b ? .doubleValue(a) : nil
case .stringValue(let b):
return a > Double(b) ? .doubleValue(a) : nil
}
case .stringValue(let a):
switch b {
case .intValue(let b):
return a > Int(b) ? .stringValue(a) : nil
case .doubleValue(let b):
return a > Double(b) ? .stringValue(a) : nil
case .stringValue(let b):
return a > b ? .stringValue(a) : nil
}
}
return nil
}
// Create a function that takes a string and returns a string in which each
// character is repeated once.
// Examples
// doubleChar("String") ==> "SSttrriinngg"
// doubleChar("Hello World!") ==> "HHeelllloo WWoorrlldd!!"
// doubleChar("1234!_ ") ==> "11223344!!__ "
// Notes
// The input is a string (str). No spaces and all lowercase letters.
//
func doubleChar(str: String) -> String {
return String(str.map { $0 * 2 })
}
// Create a function that takes a number as an argument, increments the number
// by one and returns the result.
// Examples
// nextValue(0) ==> 1
// nextValue(9) ==> 10
// nextValue(-3) ==> -2
// Notes
// Your function should return a number.
// Input number might be negative.
func nextValue(n: Int) -> Int {
return n + 1
}
// Create a function that takes a number as an argument, increments the number
// by one and returns the result.
// Examples
// nextValue(0) ==> 1
// nextValue(9) ==> 10
// nextValue(-3) ==> -2
// Notes
// Your function should return a number.
// Input number might be negative.
func nextValue(n: Int) -> Int {
return n + 1
}
// Create a function that takes a number as an argument, increments the number
// by one and returns the result.
// Examples
// nextValue(0) ==> 1
// nextValue(9) ==> 10
// nextValue(-3) ==> -2
// Notes
// Your function should return a number.
// Input number might be negative.
func nextValue(n: Int) -> Int {
return n + 1
}
// Create a function that takes a number as an argument, increments the number
// by one and returns the result.
// Examples
// nextValue(0) ==> 1
// nextValue(9) ==> 10
// nextValue(-3) ==> -2
// Notes
// Your function should return a number.
// Input number might be negative.
func nextValue(n: Int) -> Int {
return n + 1
}
// Create a function that takes a number as an argument, increments the number
// by one and returns the result.
// Examples
// nextValue(0) ==> 1
// nextValue(9) ==> 10
// nextValue(-3) ==> -2
// Notes
// Your function should return a number.
// Input number might be negative.
func nextValue(n: Int) -> Int {
return n +
return a > b ? .intValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Int(b) ? .intValue(a) : nil // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return a > b ? .doubleValue(a) : nil // cannot convert value of type 'Double' to expected argument type 'Int'
return a > Double(b) ? .doubleValue(a) : nil // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return a > Int(b) ? .stringValue(a) : nil // cannot convert value of type 'String' to expected argument type 'Int'
return a > Double(b) ? .stringValue(a) : nil // binary operator '>' cannot be applied to operands of type 'String' and 'Double'
return String(str.map { $0 * 2 }) // no exact matches in call to initializer
return String(str.map { $0 * 2 }) // binary operator '*' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'Int'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 2. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 3. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 4. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 5. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 6. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 7. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I love cats") == "lv cts"
// removeVowels("Hello world") == "Hll wrld"
func removeVowels(str: String) -> String {
var result = ""
for char in str {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 8. Write a function that takes a string as an argument and returns the string with all the vowels removed.
// Example
// removeVowels("I
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
func sum(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
func sumMultiplesOf3Or5(n: Int) -> Int {
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\)
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
// 1.1.11
// Write a function that takes a number n and returns the sum of all numbers from 1 to n.
// Example
// sum(1) == 1
// sum(2) == 2 + 1
// sum(3) == 2 + 1 + 2
// sum(4) == 2 + 1 + 2 + 2
func sum(n: Int) -> Int {
return (1...n).reduce(0, { $0 + $1 })
}
// 1.1.12
// Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(1) == 0
// sumMultiplesOf3Or5(2) == 0
// sumMultiplesOf3Or5(3) == 3
// sumMultiplesOf3Or5(4) == 3
// sumMultiplesOf3Or5(5) == 8
// sumMultiplesOf3Or5(6) == 8
// sumMultiplesOf3Or5(7) == 8
// sumMultiplesOf3Or5(8) == 13
// sumMultiplesOf3Or5(9) == 13
// sumMultiplesOf3Or5(10) == 13
func sumMultiplesOf3Or5(n: Int) -> Int {
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\)
}
// 1.1.13
// Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(1) == 0
// sumMultiplesOf3Or5(2) == 0
// sumMultiplesOf3Or5(3) == 3
// sumMultiplesOf3Or5(4) == 3
// sumMultiplesOf3Or5(5) == 8
// sumMultiplesOf3Or5(6) == 8
// sumMultiplesOf3Or5(7) == 8
// sumMultiplesOf3Or5(8) == 13
// sumMultiplesOf3Or5(9) == 13
// sumMultiplesOf3Or5(10) == 13
func sumMultiplesOf3Or5(n: Int) -> Int {
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\)
}
// 1.1.14
// Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(1) == 0
// sumMultiplesOf3Or5(2) == 0
// sumMultiplesOf3Or5(3) == 3
// sumMultiplesOf3Or5(4) == 3
// sumMultiplesOf3Or5(5) == 8
// sumMultiplesOf3Or5(6) == 8
// sumMultiplesOf3Or5(7) == 8
// sumMultiplesOf3Or5(8) == 13
// sumMultiplesOf3Or5(9) == 13
// sumMultiplesOf3Or5(10) == 13
func sumMultiplesOf3Or5(n: Int) -> Int {
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\)
}
// 1.1.15
// Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(1) == 0
// sumMultiplesOf3Or5(2) == 0
// sumMultiplesOf3Or5(3) == 3
// sumMultiplesOf3Or5(4) == 3
// sumMultiplesOf3Or5(5) == 8
// sumMultiplesOf3Or5(6) == 8
//
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\) // expected expression path in Swift key path
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\) // missing argument for parameter #2 in call
return (1...n).filter(isMultipleOf3Or5).reduce(0, \+\) // cannot find 'isMultipleOf3Or5' in scope
func isEqualToSumEven(n: Int) -> Bool {
let sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
let sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 2. Write a function that takes a string as input and returns the string reversed.
// Example
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// 3. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 4. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 5. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 6. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 7. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 8. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 9. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
// Example
// The binary representation of 1234 is 10011010010, so the function should return 5 in this case
func countSetBits(n: Int) -> Int {
let binary = String(UInt(n), radix: 2)
return binary.count(for: Character.one)
}
// 10. Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number, ignoring the leading zeros.
sum += i // left side of mutating operator isn't mutable: 'sum' is a 'let' constant
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
return binary.count(for: Character.one) // cannot call value of non-function type 'Int'
return binary.count(for: Character.one) // type 'Character' has no member 'one'
return binary.count(for: Character.one) // type 'Character' has no member 'one'
return binary.count(for: Character.one) // cannot call value of non-function type 'Int'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func sumSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i * i
}
return sum
}
func sumDivisibleByThreeOrFive(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
func sumDivisibleBySevenOrEleven(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 7 == 0 || i % 11 == 0 {
sum += i
}
}
return sum
}
func sumDivisibleByThirteenOrSeventeen(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 13 == 0 || i % 17 == 0 {
sum += i
}
}
return sum
}
func sumDivisibleByNineteenOrTwentyThree(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 19 == 0 || i % 23 == 0 {
sum += i
}
}
return sum
}
func sumDivisibleByNineteenOrTwentyThreeOrThirtyNine(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 19 == 0 || i % 23 == 0 || i % 29 == 0 {
sum += i
}
}
return sum
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 12. Write a function that takes a number n and returns the sum of all square numbers up to and including n.
// Example
// sumSquares(n: 4) == 30
// sumSquares(n: 5) == 55
func sumSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i * i
}
return sum
}
// 13. Write a function that takes a number n and returns the sum of all numbers up to and including n that are divisible by 3 or 5.
// Example
// sumDivisibleByThreeOrFive(n: 10) == 23
// sumDivisibleByThreeOrFive(n: 15) == 45
func sumDivisibleByThreeOrFive(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 14. Write a function that takes a number n and returns the sum of all numbers up to and including n that are divisible by 7 or 11.
// Example
// sumDivisibleBySevenOrEleven(n: 10) == 30
// sumDivisibleBySevenOrEleven(n: 15) == 60
func sumDivisibleBySevenOrEleven(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 7 == 0 || i % 11 == 0 {
sum += i
}
}
return sum
}
// 15. Write a function that takes a number n and returns the sum of all numbers up to and including n that are divisible by 13 or 17.
// Example
// sumDivisibleByThirteenOrSeventeen(n: 10) == 30
// sumDivisibleByThirteenOrSeventeen(n: 15) == 60
func sumDivisibleByThirteenOrSeventeen(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 13 == 0 || i % 17 == 0 {
sum += i
}
}
return sum
}
// 16. Write a function that takes a number n and returns the sum of all numbers up to and including n that are divisible by 19 or 23.
// Example
// sumDivisibleByNineteenOrTwentyThree(n: 10) == 30
// sumDivisibleByNineteenOrTwentyThree(n: 15) == 60
func sumDivisibleByNineteenOrTwentyThree(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 19 == 0 || i % 23 == 0 {
sum += i
}
}
return sum
}
// 17. Write a function that takes a number n and returns the sum of all numbers up to and including n that are divisible by 19, 23, or 29.
// Example
// sumDivisibleByNineteenOrTwentyThreeOrThirtyNine(n: 10) == 30
// sumDivisibleByNineteenOrTwentyThreeOrThirtyNine(n: 15) == 60
func sumDivisibleByNineteenOrTwentyThreeOrThirtyNine(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 19 == 0 || i % 23 == 0 || i % 29 == 0 {
sum += i
}
}
return sum
}
// 18. Write a function that takes
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
let sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n * 4
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
if char.isLetter {
count += 1
}
}
return count
}
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper {
count += 1
}
}
return count
}
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char.isLower {
count += 1
}
}
return count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
let sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n * 4
}
// 1.1.2
// Write a function that takes a string as an argument and returns the number of vowels in the string.
// Example
// countVowels("Hello world") == 3
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 1.1.3
// Write a function that takes a string as an argument and returns the number of words in the string.
// Example
// countWords("Hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 1.1.4
// Write a function that takes a string as an argument and returns the number of consonants in the string.
// Example
// countConsonants("Hello world") == 5
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
continue
}
if char.isLetter {
count += 1
}
}
return count
}
// 1.1.5
// Write a function that takes a string as an argument and returns the number of uppercase letters in the string.
// Example
// countUppercase("Hello world") == 2
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper {
count += 1
}
}
return count
}
// 1.1.6
// Write a function that takes a string as an argument and returns the number of lowercase letters in the string.
// Example
// countLowercase("Hello world") == 8
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char.isLower {
count += 1
}
}
return count
}
// 1.1.7
// Write a function that takes a string as an argument and returns the number of digits in the string.
// Example
// countDigits("Hello world") == 0
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
// 1.1.8
// Write a function that takes a string as an argument and returns the number of words in the string.
// Example
// countWords("Hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 1.1.9
// Write a function that takes a string as an argument and returns the number of words in the string.
// Example
// countWords("Hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 1.1.10
// Write a function that takes a string as an argument and returns the number of words in the string.
// Example
// countWords("Hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 1.1.11
// Write a function that takes a string as an argument and returns the number of words in the string.
// Example
// countWords("Hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 1.1.1
sum += i // left side of mutating operator isn't mutable: 'sum' is a 'let' constant
if char.isUpper { // value of type 'Character' has no member 'isUpper'
if char.isLower { // value of type 'Character' has no member 'isLower'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
count += 1
}
}
return count
}
func countUpperCaseLetters(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowerCaseLetters(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 1.1.10
// Write a function that takes a string as input and returns the number of vowels in the string.
// Example
// countVowels("Hello World") == 3
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 1.1.11
// Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("Hello World") == 2
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
// 1.1.12
// Write a function that takes a string as input and returns the number of consonants in the string.
// Example
// countConsonants("Hello World") == 5
func countConsonants(string: String) -> Int {
var count = 0
for char in string {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != " " {
count += 1
}
}
return count
}
// 1.1.13
// Write a function that takes a string as input and returns the number of uppercase letters in the string.
// Example
// countUpperCaseLetters("Hello World") == 2
func countUpperCaseLetters(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
// 1.1.14
// Write a function that takes a string as input and returns the number of lowercase letters in the string.
// Example
// countLowerCaseLetters("Hello World") == 5
func countLowerCaseLetters(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
// 1.1.15
// Write a function that takes a string as input and returns the number of digits in the string.
// Example
// countDigits("Hello World") == 0
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
// 1.1.16
// Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("Hello World") == 2
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
// 1.1.17
// Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("Hello World") == 2
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == " " {
count += 1
}
}
return count + 1
}
// 1.1.18
// Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("Hello World") == 2
func countWords(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
func countWordsStartingWithVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
if word.first == "a" || word.first == "e" || word.first == "i" || word.first == "o" || word.first == "u" {
count += 1
}
}
return count
}
func countWordsEndingWithVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
if word.last == "a" || word.last == "e" || word.last == "i" || word.last == "o" || word.last == "u" {
count += 1
}
}
return count
}
func countWordsContainingVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
for char in word {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
break
}
}
}
return count
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 1. Write a function that takes a string as input and returns the number of vowels in the string.
// Example
// countVowels("hello world") == 3
func countVowels(string: String) -> Int {
var count = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// 2. Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("hello world") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// 3. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// Example
// countUppercase("Hello World") == 2
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.uppercase {
count += 1
}
}
return count
}
// 4. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// Example
// countLowercase("Hello World") == 5
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char == char.lowercase {
count += 1
}
}
return count
}
// 5. Write a function that takes a string as input and returns the number of digits in the string.
// Example
// countDigits("12345") == 5
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
// 6. Write a function that takes a string as input and returns the number of words that start with a vowel.
// Example
// countWordsStartingWithVowel("hello world") == 1
func countWordsStartingWithVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
if word.first == "a" || word.first == "e" || word.first == "i" || word.first == "o" || word.first == "u" {
count += 1
}
}
return count
}
// 7. Write a function that takes a string as input and returns the number of words that end with a vowel.
// Example
// countWordsEndingWithVowel("hello world") == 1
func countWordsEndingWithVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
if word.last == "a" || word.last == "e" || word.last == "i" || word.last == "o" || word.last == "u" {
count += 1
}
}
return count
}
// 8. Write a function that takes a string as input and returns the number of words that contain a vowel.
// Example
// countWordsContainingVowel("hello world") == 2
func countWordsContainingVowel(string: String) -> Int {
var count = 0
for word in string.split(separator: " ") {
for char in word {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
break
}
}
}
return count
}
// 9. Write a function that takes a string as input and returns the number of words that contain all vowels.
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
func sum(n: Int) -> Int {
return (1 + n) * n / 2
}
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
// 2. Write a function that takes a number n and returns the sum of all numbers from 1 to n.
// Example
// sum(n: 5) == 15
// sum(n: 10) == 55
func sum(n: Int) -> Int {
return (1 + n) * n / 2
}
// 3. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 4. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 5. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 6. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 7. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 8. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 9. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n + 1) / 2)
}
// 10. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
return sum(n: (n +
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
func sum(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
// 10. Write a function that takes a number n and returns the sum of all numbers from 1 to n.
// Example
// sum(n: 5) == 15
// sum(n: 10) == 55
func sum(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// 11. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 12. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 13. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 14. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 15. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// 16. Write a function that takes a number n and returns the sum of all numbers from 1 to n that are multiples of 3 or 5.
// Example
// sumMultiplesOf3Or5(n: 10) == 33
// sumMultiplesOf3Or5(n: 15) == 45
func sumMultiplesOf3Or5(n: Int) -> Int {
var sum = 0
for
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
func countVowels(string: String) -> Int {
return string.count(for: .vowel)
}
func countWords(string: String) -> Int {
return string.split(.whitespace).count
}
func countConsonants(string: String) -> Int {
return string.count(for: .consonant)
}
func countUppercase(string: String) -> Int {
return string.count(for: .uppercaseLetter)
}
func countLowercase(string: String) -> Int {
return string.count(for: .lowercaseLetter)
}
func countDigits(string: String) -> Int {
return string.count(for: .digit)
}
func countWordsStartingWithVowel(string: String) -> Int {
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count
}
func countWordsEndingWithConsonant(string: String) -> Int {
return string.split(.whitespace).filter { $0.last == "a" || $0.last == "e" || $0.last == "i" || $0.last == "o" || $0.last == "u" }.count
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
return n % 2 == 0 && n % 4 == 0
}
// 2. Write a function that takes a string as input and returns the number of vowels in the string.
// Example
// countVowels("hello") == 2
// countVowels("apple") == 2
// countVowels("banana") == 3
func countVowels(string: String) -> Int {
return string.count(for: .vowel)
}
// 3. Write a function that takes a string as input and returns the number of words in the string.
// Example
// countWords("hello world") == 2
// countWords("apple banana") == 2
// countWords("banana apple") == 2
func countWords(string: String) -> Int {
return string.split(.whitespace).count
}
// 4. Write a function that takes a string as input and returns the number of consonants in the string.
// Example
// countConsonants("hello") == 3
// countConsonants("apple") == 4
// countConsonants("banana") == 5
func countConsonants(string: String) -> Int {
return string.count(for: .consonant)
}
// 5. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// Example
// countUppercase("Hello") == 1
// countUppercase("Apple") == 2
// countUppercase("Banana") == 3
func countUppercase(string: String) -> Int {
return string.count(for: .uppercaseLetter)
}
// 6. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// Example
// countLowercase("Hello") == 1
// countLowercase("Apple") == 2
// countLowercase("Banana") == 3
func countLowercase(string: String) -> Int {
return string.count(for: .lowercaseLetter)
}
// 7. Write a function that takes a string as input and returns the number of digits in the string.
// Example
// countDigits("123") == 3
// countDigits("apple") == 0
// countDigits("banana") == 3
func countDigits(string: String) -> Int {
return string.count(for: .digit)
}
// 8. Write a function that takes a string as input and returns the number of words that start with a vowel.
// Example
// countWordsStartingWithVowel("hello world") == 1
// countWordsStartingWithVowel("apple banana") == 1
// countWordsStartingWithVowel("banana apple") == 2
func countWordsStartingWithVowel(string: String) -> Int {
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count
}
// 9. Write a function that takes a string as input and returns the number of words that end with a consonant.
// Example
// countWordsEndingWithConsonant("hello world") == 1
// countWordsEndingWithConsonant("apple banana") == 1
// countWordsEndingWithConsonant("banana apple") == 2
func countWordsEndingWithConsonant(string: String) -> Int {
return string.split(.whitespace).filter { $0.last == "a" || $0.last == "e" || $0.last == "i" || $0.last == "o" || $0.last == "u" }.count
}
// 10. Write a function that takes a string as input and returns the number of words that contain only digits.
// Example
// countWordsContainingDigits("123") == 1
return string.count(for: .vowel) // cannot infer contextual base in reference to member 'vowel'
return string.count(for: .vowel) // cannot call value of non-function type 'Int'
return string.split(.whitespace).count // no exact matches in call to instance method 'split'
return string.split(.whitespace).count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return string.count(for: .consonant) // cannot infer contextual base in reference to member 'consonant'
return string.count(for: .consonant) // cannot call value of non-function type 'Int'
return string.count(for: .uppercaseLetter) // cannot infer contextual base in reference to member 'uppercaseLetter'
return string.count(for: .uppercaseLetter) // cannot call value of non-function type 'Int'
return string.count(for: .lowercaseLetter) // cannot call value of non-function type 'Int'
return string.count(for: .lowercaseLetter) // cannot infer contextual base in reference to member 'lowercaseLetter'
return string.count(for: .digit) // cannot infer contextual base in reference to member 'digit'
return string.count(for: .digit) // cannot call value of non-function type 'Int'
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return string.split(.whitespace).filter { $0.first == "a" || $0.first == "e" || $0.first == "i" || $0.first == "o" || $0.first == "u" }.count // no exact matches in call to instance method 'split'
return string.split(.whitespace).filter { $0.last == "a" || $0.last == "e" || $0.last == "i" || $0.last == "o" || $0.last == "u" }.count // type 'String.Element' (aka 'Character') has no member 'whitespace'
return string.split(.whitespace).filter { $0.last == "a" || $0.last == "e" || $0.last == "i" || $0.last == "o" || $0.last == "u" }.count // no exact matches in call to instance method 'split'
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func sumArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 })
}
func maxArray(array: [Int]) -> Int {
return array.max()!
}
func minArray(array: [Int]) -> Int {
return array.min()!
}
func averageArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 }) / array.count
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string
// reversed.
// Example:
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an array of integers as input and returns the
// sum of all the integers in the array.
// Example:
// sumArray([1, 2, 3]) == 6
func sumArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes an array of integers as input and returns the
// maximum value in the array.
// Example:
// maxArray([1, 2, 3]) == 3
func maxArray(array: [Int]) -> Int {
return array.max()!
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an array of integers as input and returns the
// minimum value in the array.
// Example:
// minArray([1, 2, 3]) == 1
func minArray(array: [Int]) -> Int {
return array.min()!
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes an array of integers as input and returns the
// average value in the array.
// Example:
// averageArray([1, 2, 3]) == 2
func averageArray(array: [Int]) -> Int {
return array.reduce(0, { $0 + $1 }) / array.count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes an array of integers as input and returns the
// median value in the array.
// Example:
// medianArray([1, 2, 3]) == 2
func medianArray(array: [Int]) -> Int {
return array.sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().sorted().
return string.reversed().join() // reference to member 'join' cannot be resolved without a contextual type
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func firstUniqChar(s: String) -> Int {
var dict = [String: Int]()
for (i, c) in s.enumerate() {
if dict[c] != nil {
dict[c] = -1
} else {
dict[c] = i
}
}
var min = Int.max
for (key, value) in dict {
if value != -1 && value < min {
min = value
}
}
return min == Int.max ? -1 : min
}
func longestPalindrome(s: String) -> String {
var max = String()
for (i, c) in s.enumerate() {
var left = i
var right = i
while left >= 0 && right < s.count && s[left] == s[right] {
if right - left + 1 > max.count {
max = s[left..<right + 1]
}
left -= 1
right += 1
}
left = i
right = i + 1
while left >= 0 && right < s.count && s[left] == s[right] {
if right - left + 1 > max.count {
max = s[left..<right + 1]
}
left -= 1
right += 1
}
}
return max
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func reverseString(s: String) -> String {
return String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given a string s, find the first non-repeating character in it and return its
// index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
func firstUniqChar(s: String) -> Int {
var dict = [String: Int]()
for (i, c) in s.enumerate() {
if dict[c] != nil {
dict[c] = -1
} else {
dict[c] = i
}
}
var min = Int.max
for (key, value) in dict {
if value != -1 && value < min {
min = value
}
}
return min == Int.max ? -1 : min
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Given a string s, find the longest palindromic substring in s. You may assume
// that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = String()
for (i, c) in s.enumerate() {
var left = i
var right = i
while left >= 0 && right < s.count && s[left] == s[right] {
if right - left + 1 > max.count {
max = s[left..<right + 1]
}
left -= 1
right += 1
}
left = i
right = i + 1
while left >= 0 && right < s.count && s[left] == s[right] {
if right - left + 1 > max.count {
max = s[left..<right + 1]
}
left -= 1
right += 1
}
}
return max
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Given a string s, find the longest palindromic substring in s. You may assume
// that the maximum length of s is 1000.
// Example:
// Input: "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: "cbbd"
// Output: "bb"
func longestPalindrome(s: String) -> String {
var max = String()
for (i, c) in s.enumerate() {
var left = i
var right = i
while left >= 0 && right < s.count &&
for (i, c) in s.enumerate() { // value of type 'String' has no member 'enumerate'
for (i, c) in s.enumerate() { // value of type 'String' has no member 'enumerate'
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func numberOfVowels(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
func numberOfLetters(string: String) -> [String: Int] {
var result = [String: Int]()
for char in string {
if result.keys.contains(char) {
result[char]! += 1
} else {
result[char] = 1
}
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the number of
// vowels in the string.
// The vowels are: a, e, i, o, u
// For example:
// numberOfVowels("abracadabra") == 5
func numberOfVowels(string: String) -> Int {
var result = 0
for char in string {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the number of
// times a letter appears in the string.
// The letter can be upper or lower case.
// For example:
// numberOfLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 2, "W": 1, "r": 1, "d": 1}
func numberOfLetters(string: String) -> [String: Int] {
var result = [String: Int]()
for char in string {
if result.keys.contains(char) {
result[char]! += 1
} else {
result[char] = 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the number of
// times a letter appears in the string.
// The letter can be upper or lower case.
// For example:
// numberOfLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 2, "W": 1, "r": 1, "d": 1}
func numberOfLetters(string: String) -> [String: Int] {
var result = [String: Int]()
for char in string {
if result.keys.contains(char) {
result[char]! += 1
} else {
result[char] = 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the number of
// times a letter appears in the string.
// The letter can be upper or lower case.
// For example:
// numberOfLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 2, "W": 1, "r": 1, "d": 1}
func numberOfLetters(string: String) -> [String: Int] {
var result = [String: Int]()
for char in string {
if result.keys.contains(char) {
result[char]! += 1
} else {
result[char] = 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as input and returns the number of
// times a letter appears in the string.
// The letter can be upper or lower case.
// For example:
// numberOfLetters("Hello World") == {"H": 1, "e": 1, "l": 2, "o": 2, " ": 2, "W": 1, "r": 1, "d": 1}
func numberOfLetters(string: String) -> [
if result.keys.contains(char) { // cannot convert value of type 'Character' to expected argument type 'Dictionary<String, Int>.Keys.Element' (aka 'String')
result[char]! += 1 // cannot convert value of type 'Character' to expected argument type 'String'
result[char] = 1 // cannot convert value of type 'Character' to expected argument type 'String'
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 5. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 6. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char !=
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.2
// Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.3
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.4
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.5
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.6
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ----------------------------------------------------------------------------------------------------------------------
// 1.1.7
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
// ---------------------------------------------------------------------------------------------------
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// 2. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 3. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 4. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 5. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// 6. Write a function that takes a string and returns a new string with all the vowels removed.
// removeVowels(text: "Example") == "Exmpl"
// removeVowels(text: "Example 1") == "Exmpl 1"
// removeVowels(text: "Example 2") == "Exmpl 2"
// removeVowels(text: "Example 3") == "Exmpl 3"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if char !=
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last() == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last() == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
// 2. Given an array of integers, find the one that appears an odd number of times.
// findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5
// findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1
// findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5
// findOdd([10]) == 10
// findOdd([1,1,1,1,1,1,10,1,1,1,1]) == 10
// findOdd([5,4,3,2,1,5,4,3,2,10,10]) == 1
// 3. Given an array of integers, find the one that appears an odd number of times.
// findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5
// findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1
// findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5
// findOdd([10]) == 10
// findOdd([1,1,1,1,1,1,10,1,1,1,1]) == 10
// findOdd([5,4,3,2,1,5,4,3,2,10,10]) == 1
// 4. Given an array of integers, find the one that appears an odd number of times.
// findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5
// findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1
// findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5
// findOdd([10]) == 10
// findOdd([1,1,1,1,1,1,10,1,1,1,1]) == 10
// findOdd([5,4,3,2,1,5,4,3,2,10,10]) == 1
// 5. Given an array of integers, find the one that appears an odd number of times.
// findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) == 5
// findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]) == -1
// findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]) == 5
// findOdd([10]) == 10
// findOdd([1,1,1,1,1,1,10,1,1,1,1]) == 10
// findOdd([5,4,3,2,1,5,4,3,2,10,10]) == 1
// 6. Given an array of integers, find the one that appears an odd number of times.
// findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,
if result.last() == " " { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
if result.last == " " {
result += "-"
} else {
result += "_"
}
} else {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
func countVowels(text: String) -> Int {
var result = 0
for char in text {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
func countWords(text: String) -> Int {
var result = 0
for _ in text {
result += 1
}
return result
}
func countSentences(text: String) -> Int {
var result = 0
for _ in text {
if text.contains(".") || text.contains("!") || text.contains("?") {
result += 1
}
}
return result
}
func countUppercase(text: String) -> Int {
var result = 0
for char in text {
if char == char.uppercase {
result += 1
}
}
return result
}
func countLowercase(text: String) -> Int {
var result = 0
for char in text {
if char == char.lowercase {
result += 1
}
}
return result
}
func countDigits(text: String) -> Int {
var result = 0
for char in text {
if char == char.digit {
result += 1
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// 10. Write a function that takes a string as input and returns the number of vowels in the string.
// countVowels("Hello World") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels("Aa") == 2
func countVowels(text: String) -> Int {
var result = 0
for char in text {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
result += 1
}
}
return result
}
// 11. Write a function that takes a string as input and returns the number of words in the string.
// countWords("Hello World") == 2
// countWords("Hello") == 1
// countWords("") == 0
// countWords("Aa") == 1
func countWords(text: String) -> Int {
var result = 0
for _ in text {
result += 1
}
return result
}
// 12. Write a function that takes a string as input and returns the number of sentences in the string.
// countSentences("Hello World!") == 1
// countSentences("Hello World! How are you?") == 2
// countSentences("") == 0
// countSentences("Aa") == 1
func countSentences(text: String) -> Int {
var result = 0
for _ in text {
if text.contains(".") || text.contains("!") || text.contains("?") {
result += 1
}
}
return result
}
// 13. Write a function that takes a string as input and returns the number of uppercase letters in the string.
// countUppercase("Hello World") == 2
// countUppercase("Hello") == 0
// countUppercase("") == 0
// countUppercase("Aa") == 2
func countUppercase(text: String) -> Int {
var result = 0
for char in text {
if char == char.uppercase {
result += 1
}
}
return result
}
// 14. Write a function that takes a string as input and returns the number of lowercase letters in the string.
// countLowercase("Hello World") == 5
// countLowercase("Hello") == 5
// countLowercase("") == 0
// countLowercase("Aa") == 2
func countLowercase(text: String) -> Int {
var result = 0
for char in text {
if char == char.lowercase {
result += 1
}
}
return result
}
// 15. Write a function that takes a string as input and returns the number of digits in the string.
// countDigits("Hello World") == 0
// countDigits("Hello") == 0
// countDigits("") == 0
// countDigits("Aa") == 0
// countDigits("123") == 3
func countDigits(text: String) -> Int {
var result = 0
for char in text {
if char == char.digit {
result += 1
}
}
return result
}
// 16. Write a function that takes a string as input and returns the number of alphabetic characters in the string.
// countAlphabetic("Hello World") == 5
// countAlphabetic("Hello") == 5
// countAlphabetic("") == 0
// countAlphabetic("
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char == char.digit { // value of type 'Character' has no member 'digit'
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
for char in text {
if char == " " {
result += "_"
} else if result.last() == "_" {
result += "-"
} else {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------
} else if result.last() == "_" { // cannot call value of non-function type 'String.Element?' (aka 'Optional<Character>')
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let name = split[0]
let extension = split[1]
if name.count > 3 {
return "No"
}
if name.first!.isLetter {
return "No"
}
if extension.count != 3 {
return "No"
}
if extension != "txt" && extension != "exe" && extension != "dll" {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let name = split[0]
let extension = split[1]
if name.count > 3 {
return "No"
}
if name.first!.isLetter {
return "No"
}
if extension.count != 3 {
return "No"
}
if extension != "txt" && extension != "exe" && extension != "dll" {
return "No"
}
return "Yes"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let extension = split[1] // keyword 'extension' cannot be used as an identifier here
if extension.count != 3 { // expected type name in extension declaration
if extension.count != 3 { // declaration is only valid at file scope
if extension.count != 3 { // expected expression, var, or let in 'if' condition
if extension.count != 3 { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // expected expression, var, or let in 'if' condition
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
func fileNameCheck(fileName: String) -> String {
let fileNameArray = fileName.split(separator: ".")
if fileNameArray.count != 2 {
return "No"
}
let fileName = fileNameArray[0]
let extension = fileNameArray[1]
if fileName.length > 3 {
return "No"
}
if extension.length != 3 {
return "No"
}
if !extension.isLetter() {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileNameArray = fileName.split(separator: ".")
if fileNameArray.count != 2 {
return "No"
}
let fileName = fileNameArray[0]
let extension = fileNameArray[1]
if fileName.length > 3 {
return "No"
}
if extension.length != 3 {
return "No"
}
if !extension.isLetter() {
return "No"
}
return "Yes"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let extension = fileNameArray[1] // keyword 'extension' cannot be used as an identifier here
if fileName.length > 3 { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if extension.length != 3 { // expected type name in extension declaration
if extension.length != 3 { // expected expression, var, or let in 'if' condition
if extension.length != 3 { // expected '{' in extension
if extension.length != 3 { // declaration is only valid at file scope
if !extension.isLetter() { // expected expression, var, or let in 'if' condition
if !extension.isLetter() { // expected type name in extension declaration
if !extension.isLetter() { // declaration is only valid at file scope
if !extension.isLetter() { // expected '{' in extension
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let name = split[0]
let extension = split[1]
if name.count > 3 {
return "No"
}
if name.first! < "a" || name.first! > "z" || name.first! < "A" || name.first! > "Z" {
return "No"
}
if extension != "txt" && extension != "exe" && extension != "dll" {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let name = split[0]
let extension = split[1]
if name.count > 3 {
return "No"
}
if name.first! < "a" || name.first! > "z" || name.first! < "A" || name.first! > "Z" {
return "No"
}
if extension != "txt" && extension != "exe" && extension != "dll" {
return "No"
}
return "Yes"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let extension = split[1] // keyword 'extension' cannot be used as an identifier here
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // expected type name in extension declaration
if extension != "txt" && extension != "exe" && extension != "dll" { // expected '{' in extension
if extension != "txt" && extension != "exe" && extension != "dll" { // expected expression, var, or let in 'if' condition
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
if extension != "txt" && extension != "exe" && extension != "dll" { // declaration is only valid at file scope
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".").last!
if fileName.count > 3 {
return "No"
}
if fileName.first! != "a" && fileName.first! != "A" && fileName.first! != "b" && fileName.first! != "B" && fileName.first! != "c" && fileName.first! != "C" && fileName.first! != "d" && fileName.first! != "D" && fileName.first! != "e" && fileName.first! != "E" && fileName.first! != "f" && fileName.first! != "F" && fileName.first! != "g" && fileName.first! != "G" && fileName.first! != "h" && fileName.first! != "H" && fileName.first! != "i" && fileName.first! != "I" && fileName.first! != "j" && fileName.first! != "J" && fileName.first! != "k" && fileName.first! != "K" && fileName.first! != "l" && fileName.first! != "L" && fileName.first! != "m" && fileName.first! != "M" && fileName.first! != "n" && fileName.first! != "N" && fileName.first! != "o" && fileName.first! != "O" && fileName.first! != "p" && fileName.first! != "P" && fileName.first! != "q" && fileName.first! != "Q" && fileName.first! != "r" && fileName.first! != "R" && fileName.first! != "s" && fileName.first! != "S" && fileName.first! != "t" && fileName.first! != "T" && fileName.first! != "u" && fileName.first! != "U" && fileName.first! != "v" && fileName.first! != "V" && fileName.first! != "w" && fileName.first! != "W" && fileName.first! != "x" && fileName.first! != "X" && fileName.first! != "y" && fileName.first! != "Y" && fileName.first! != "z" && fileName.first! != "Z" {
return "No"
}
if fileName.last! != "txt" && fileName.last! != "exe" && fileName.last! != "dll" {
return "No"
}
return "Yes"
}
struct FileNameCheck_Tests {
static let allTests = [
TestCase(name: "Example", function: fileNameCheck, arguments: ("example.txt",), expected: "Yes"),
TestCase(name: "1example.dll", function: fileNameCheck, arguments: ("1example.dll",), expected: "No"),
]
static func run() {
for t in allTests {
print("Running test: \(t.name)")
if (t.function(t.arguments.first!) != t.expected) {
print(" FAILED")
} else {
print(" OK")
}
}
}
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".").last!
if fileName.count > 3 {
return "No"
}
if fileName.first! != "a" && fileName.first! != "A" && fileName.first! != "b" && fileName.first! != "B" && fileName.first! != "c" && fileName.first! != "C" && fileName.first! != "d" && fileName.first! != "D" && fileName.first! != "e" && fileName.first! != "E" && fileName.first! != "f" && fileName.first! != "F" && fileName.first! != "g" && fileName.first! != "G" && fileName.first! != "h" && fileName.first! != "H" && fileName.first! != "i" && fileName.first! != "I" && fileName.first! != "j" && fileName.first! != "J" && fileName.first! != "k" && fileName.first! != "K" && fileName.first! != "l" && fileName.first! != "L" && fileName.first! != "m" && fileName.first! != "M" && fileName.first! != "n" && fileName.first! != "N" && fileName.first! != "o" && fileName.first! != "O" && fileName.first! != "p" && fileName.first! != "P" && fileName.first! != "q" && fileName.first! != "Q" && fileName.first! != "r" && fileName.first! != "R" && fileName.first! != "s" && fileName.first! != "S" && fileName.first! != "t" && fileName.first! != "T" && fileName.first! != "u" && fileName.first! != "U" && fileName.first! != "v" && fileName.first! != "V" && fileName.first! != "w" && fileName.first! != "W" && fileName.first! != "x" && fileName.first! != "X" && fileName.first! != "y" && fileName.first! != "Y" && fileName.first! != "z" && fileName.first! != "Z" {
return "No"
}
if fileName.last! != "txt" && fileName.last! != "exe" && fileName.last! != "dll" {
return "No"
}
return "Yes"
}
// -----------------------------------------------------------------------------
struct FileNameCheck_Tests {
static let allTests = [
TestCase(name: "Example", function: fileNameCheck, arguments: ("example.txt",), expected: "Yes"),
TestCase(name: "1example.dll", function: fileNameCheck, arguments: ("1example.dll",), expected: "No"),
]
static func run() {
for t in allTests {
print("Running test: \(t.name)")
if (t.function(t.arguments.first!) != t.expected) {
print(" FAILED")
} else {
print(" OK")
}
}
}
}<|endoftext|>// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
if fileName.last! != "txt" && fileName.last! != "exe" && fileName.last! != "dll" { // conflicting arguments to generic parameter 'Self' ('Substring.Element' vs. 'String')
if fileName.last! != "txt" && fileName.last! != "exe" && fileName.last! != "dll" { // conflicting arguments to generic parameter 'Self' ('Substring.Element' vs. 'String')
if fileName.last! != "txt" && fileName.last! != "exe" && fileName.last! != "dll" { // conflicting arguments to generic parameter 'Self' ('Substring.Element' vs. 'String')
TestCase(name: "Example", function: fileNameCheck, arguments: ("example.txt",), expected: "Yes"), // cannot find 'TestCase' in scope
TestCase(name: "Example", function: fileNameCheck, arguments: ("example.txt",), expected: "Yes"), // unexpected ',' separator
TestCase(name: "1example.dll", function: fileNameCheck, arguments: ("1example.dll",), expected: "No"), // cannot find 'TestCase' in scope
TestCase(name: "1example.dll", function: fileNameCheck, arguments: ("1example.dll",), expected: "No"), // unexpected ',' separator
func fileNameCheck(fileName: String) -> String {
let parts = fileName.split(separator: ".")
if parts.count != 2 {
return "No"
}
let name = parts[0]
let extension = parts[1]
if name.length > 3 {
return "No"
}
if extension.length != 3 {
return "No"
}
let validExtensions = ["txt", "exe", "dll"]
if !validExtensions.contains(extension) {
return "No"
}
let validName = name.first!.isLetter
if !validName {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let parts = fileName.split(separator: ".")
if parts.count != 2 {
return "No"
}
let name = parts[0]
let extension = parts[1]
if name.length > 3 {
return "No"
}
if extension.length != 3 {
return "No"
}
let validExtensions = ["txt", "exe", "dll"]
if !validExtensions.contains(extension) {
return "No"
}
let validName = name.first!.isLetter
if !validName {
return "No"
}
return "Yes"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let extension = parts[1] // keyword 'extension' cannot be used as an identifier here
if name.length > 3 { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if extension.length != 3 { // expected type name in extension declaration
if extension.length != 3 { // expected expression, var, or let in 'if' condition
if extension.length != 3 { // expected '{' in extension
if extension.length != 3 { // declaration is only valid at file scope
if !validExtensions.contains(extension) { // expected '{' in extension
if !validExtensions.contains(extension) { // missing argument for parameter 'where' in call
if !validExtensions.contains(extension) { // expected expression in list of expressions
if !validExtensions.contains(extension) { // expected type name in extension declaration
if !validExtensions.contains(extension) { // declaration is only valid at file scope
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".")
if fileName.count > 2 {
return "No"
}
if fileName[0].count == 0 {
return "No"
}
if fileName[0].first!.isLetter {
return "No"
}
if fileName[1].count != 3 {
return "No"
}
if fileName[1].first!.isLetter {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".")
if fileName.count > 2 {
return "No"
}
if fileName[0].count == 0 {
return "No"
}
if fileName[0].first!.isLetter {
return "No"
}
if fileName[1].count != 3 {
return "No"
}
if fileName[1].first!.isLetter {
return "No"
}
return "Yes"
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let first = split[0]
let second = split[1]
if first.count > 3 {
return "No"
}
if first.first!.isLetter {
return "No"
}
if second != "txt" && second != "exe" && second != "dll" {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
if fileName.count > 10 {
return "No"
}
let split = fileName.split(separator: ".")
if split.count != 2 {
return "No"
}
let first = split[0]
let second = split[1]
if first.count > 3 {
return "No"
}
if first.first!.isLetter {
return "No"
}
if second != "txt" && second != "exe" && second != "dll" {
return "No"
}
return "Yes"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".")
if fileName.count == 1 {
return "No"
}
if fileName[0].count > 3 {
return "No"
}
if fileName[1] != "txt" && fileName[1] != "exe" && fileName[1] != "dll" {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".")
if fileName.count == 1 {
return "No"
}
if fileName[0].count > 3 {
return "No"
}
if fileName[1] != "txt" && fileName[1] != "exe" && fileName[1] != "dll" {
return "No"
}
return "Yes"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".").first!
let fileNameSplit = fileName.split(separator: ".").last!
let fileNameSplitLetters = fileNameSplit.split(separator: "").first!
let fileNameSplitLettersLetters = fileNameSplitLetters.split(separator: "").first!
let fileNameSplitLettersLettersLetters = fileNameSplitLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLetters = fileNameSplitLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters.split(separator: "").first!
let fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLettersLetters = fileNameSplitLettersLettersLettersLettersLettersLettersLettersLettersLetters
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.split(separator: ".").last!
let fileNameArray = fileName.split(separator: ".")
let fileNameArrayLength = fileNameArray.count
let fileNameArrayFirst = fileNameArray[0]
let fileNameArraySecond = fileNameArray[1]
let fileNameArraySecondLength = fileNameArraySecond.length
let fileNameArraySecondFirst = fileNameArraySecond[0]
let fileNameArraySecondSecond = fileNameArraySecond[1]
let fileNameArraySecondThird = fileNameArraySecond[2]
let fileNameArraySecondFourth = fileNameArraySecond[3]
let fileNameArraySecondFifth = fileNameArraySecond[4]
let fileNameArraySecondSixth = fileNameArraySecond[5]
let fileNameArraySecondSeventh = fileNameArraySecond[6]
let fileNameArraySecondEighth = fileNameArraySecond[7]
let fileNameArraySecondNinth = fileNameArraySecond[8]
let fileNameArraySecondTenth = fileNameArraySecond[9]
let fileNameArraySecondEleventh = fileNameArraySecond[10]
let fileNameArraySecondTwelfth = fileNameArraySecond[11]
let fileNameArraySecondThirteenth = fileNameArraySecond[12]
let fileNameArraySecondFourteenth = fileNameArraySecond[13]
let fileNameArraySecondFifteenth = fileNameArraySecond[14]
let fileNameArraySecondSixteenth = fileNameArraySecond[15]
let fileNameArraySecondSeventeenth = fileNameArraySecond[16]
let fileNameArraySecondEighteenth = fileNameArraySecond[17]
let fileNameArraySecondNineteenth = fileNameArraySecond[18]
let fileNameArraySecondTwentieth = fileNameArraySecond[19]
let fileNameArraySecondTwentyFirst = fileNameArraySecond[20]
let fileNameArraySecondTwentySecond = fileNameArraySecond[21]
let fileNameArraySecondTwentyThird = fileNameArraySecond[22]
let fileNameArraySecondTwentyFourth = fileNameArraySecond[23]
let fileNameArraySecondTwentyFifth = fileNameArraySecond[24]
let fileNameArraySecondTwentySixth = fileNameArraySecond[25]
let fileNameArraySecondTwentySeventh = fileNameArraySecond[26]
let fileNameArraySecondTwentyEighth = fileNameArraySecond[27]
let fileNameArraySecondTwentyNinth = fileNameArraySecond[28]
let fileNameArraySecondThirtieth = fileNameArraySecond[29]
let fileNameArraySecondThirtyFirst = fileNameArraySecond[30]
let fileNameArraySecondThirtySecond = fileNameArraySecond[31]
let fileNameArraySecondThirtyThird = fileNameArraySecond[32]
let fileNameArraySecondThirtyFourth = fileNameArraySecond[33]
let fileNameArraySecondThirtyFifth = fileNameArraySecond[34]
let fileNameArraySecondThirtySixth = fileNameArraySecond[35]
let fileNameArraySecondThirtySeventh = fileNameArraySecond[36]
let fileNameArraySecondThirtyEighth = fileNameArraySecond[37]
let fileNameArraySecondThirtyNinth = fileNameArraySecond[38]
let fileNameArraySecondFortieth = fileNameArraySecond[39]
let fileNameArraySecondFortyFirst = fileNameArraySecond[40]
let fileNameArraySecondFortySecond = fileNameArraySecond[41]
let fileNameArraySecondFortyThird = fileNameArraySecond[42]
let fileNameArraySecondFortyFourth = fileNameArraySecond[43]
let fileNameArraySecondFortyFifth = fileNameArraySecond[44]
let fileNameArraySecondFortySixth = fileNameArraySecond[45]
let fileNameArraySecondFortySeventh = fileNameArraySecond[46]
let fileNameArraySecondFortyEighth = fileNameArraySecond[47]
let fileNameArraySecondFortyN
XCTAssertTrue(fileNameCheck(fileName: "example.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1example.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s1sdf3.asd") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "K.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "MY16FILE3.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "His12FILE94.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "_Y.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "?aREYA.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "/thisIsValid.dll") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.wow") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIsValid.txtexe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "#this2I4s5valid.ten") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "@this1Is6Valid.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "thisIs12valid.6exe4.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "all.exe.txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_No.exe") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "Is3youfault.txt") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "noOne#knows.dll") == "Yes") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "1I563_Yes3.exe") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "I563_Yes3.txtt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final..txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "final132") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "F4indsartal132.") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: ".txt") == "No") // cannot find 'fileNameCheck' in scope
XCTAssertTrue(fileNameCheck(fileName: "s.") == "No") // cannot find 'fileNameCheck' in scope
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(by: " ")
var primeWords = ""
for word in words {
if isPrime(word.length) {
primeWords += word + " "
}
}
return primeWords.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
import Foundation
func main() {
print("Hello, World!")
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(by: " ")
var primeWords = ""
for word in words {
if isPrime(word.length) {
primeWords += word + " "
}
}
return primeWords.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// Swift-Algorithms
//
// Created by 임성현 on 2021/04/29.
//
import Foundation
func main() {
print("Hello, World!")
}
// 1. 문자열 뒤집기
// 문자열 s의 문자를 뒤집어서 새로운 문자열을 만든 후 반환하는 함수, solution을 완성해주세요.
// 예를들어 s가 "hello"면 "olleh"을 리턴하고 "안녕하세요"면 "세요녕하"를 리턴하면 됩니다.
// 제한 문자열은 1000자 이하입니다.
// 입출력 예
// s return
// "hello" "olleh"
// "안녕하세요" "세요녕하"
// 입출력 예 설명
// 입출력 예 #1
// "hello"는 여전히 hello이므로 "olleh"를 리턴합니다.
// 입출력 예 #2
// "안녕하세요"는 여전히 안녕하세요이므로 "세요녕하"를 리턴합니다.
// 입출력 예 #1
// s return
// "hello" "olleh"
// "안녕하세요" "세요녕하"
// 입출력 예 설명
// 입출력 예 #1
// "hello"는 여전히 hello이므로 "olleh"를 리턴합니다.
// 입출력 예 #2
// "안녕하세요"는 여전히 안녕하세요이므로 "세요녕하"를 리턴합니다.
// 입출력 예 #1
// s return
// "hello" "olleh"
// "안녕하세요" "세요녕하"
// 입출력 예 설명
// 입출력 예 #1
// "hello"는 여전히 hello이��
let words = sentence.split(by: " ") // no exact matches in call to instance method 'split'
return primeWords.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
var result = ""
for word in words {
if primeNumbers.contains(word.count) {
result += word + " "
}
}
return result.trim()
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
var result = ""
for word in words {
if primeNumbers.contains(word.count) {
result += word + " "
}
}
return result.trim()
}
var sentence = "This is a test"
var result = wordsInSentence(sentence)
print(result)
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var words = sentence.split(by: " ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2...number {
if number % i == 0 {
return false
}
}
return true
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2...number {
if number % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 11.1
//
// Created by 임현성 on 2022/07/14.
//
import Foundation
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sum = 0
for i in array {
sum += i
}
print(sum)
var sum2 = 0
for i in array {
if i % 2 == 0 {
sum2 += i
}
}
print(sum2)
var sum3 = 0
for i in array {
if i % 2 != 0 {
sum3 += i
}
}
print(sum3)
var sum4 = 0
for i in array {
if i % 2 == 0 {
sum4 += i
} else {
sum4 -= i
}
}
print(sum4)
var sum5 = 0
for i in array {
if i % 2 == 0 {
sum5 += i
} else {
sum5 -= i
}
}
print(sum5)
var sum6 = 0
for i in array {
if i % 2 == 0 {
sum6 += i
} else {
sum6 -= i
}
}
print(sum6)
var sum7 = 0
for i in array {
if i % 2 == 0 {
sum7 += i
} else {
sum7 -= i
}
}
print(sum7)
var sum8 = 0
for i in array {
if i % 2 == 0 {
sum8 += i
} else {
sum8 -= i
}
}
print(sum8)
var sum9 = 0
for i in array {
if i % 2 == 0 {
sum9 += i
} else {
sum9 -= i
}
}
print(sum9)
var sum10 = 0
for i in array {
if i % 2 == 0 {
sum10 += i
} else {
sum10 -= i
}
}
print(sum10)
var sum11 = 0
for i in array {
if i % 2 == 0 {
sum11 += i
} else {
sum11 -= i
}
}
print(sum11)
var sum12 = 0
for i in array {
if i % 2 == 0 {
sum12 += i
} else {
sum12 -= i
}
}
print(sum12)
var sum13 = 0
for i in array {
if i % 2 == 0 {
sum13 += i
} else {
sum13 -= i
}
}
print(sum13)
var sum14 = 0
for i in array {
if i % 2 == 0 {
sum14 += i
} else {
sum14 -= i
}
}
print(sum14)
var sum15 = 0
for i in array {
if i % 2 == 0 {
sum15 += i
} else {
sum15 -= i
}
}
print(sum15)
if isPrime(word.length) { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if isPrime(word.length) { // missing argument label 'number:' in call
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 1 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
let sentence = "This is a test"
print(wordsInSentence(sentence: sentence))
// Output:
// is
let sentence2 = "lets go for swimming"
print(wordsInSentence(sentence: sentence2))
// Output:
// go for
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
var words = sentence.split(by: " ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var words = sentence.split(by: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2..<number {
if number % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성혁 on 2021/03/10.
//
import Foundation
var num1 = 1
var num2 = 2
var num3 = 3
var num4 = 4
var num5 = 5
var num6 = 6
var num7 = 7
var num8 = 8
var num9 = 9
var num10 = 10
var num11 = 11
var num12 = 12
var num13 = 13
var num14 = 14
var num15 = 15
var num16 = 16
var num17 = 17
var num18 = 18
var num19 = 19
var num20 = 20
var num21 = 21
var num22 = 22
var num23 = 23
var num24 = 24
var num25 = 25
var num26 = 26
var num27 = 27
var num28 = 28
var num29 = 29
var num30 = 30
var num31 = 31
var num32 = 32
var num33 = 33
var num34 = 34
var num35 = 35
var num36 = 36
var num37 = 37
var num38 = 38
var num39 = 39
var num40 = 40
var num41 = 41
var num42 = 42
var num43 = 43
var num44 = 44
var num45 = 45
var num46 = 46
var num47 = 47
var num48 = 48
var num49 = 49
var num50 = 50
var num51 = 51
var num52 = 52
var num53 = 53
var num54 = 54
var num55 = 55
var num56 = 56
var num57 = 57
var num58 = 58
var num59 = 59
var num60 = 60
var num61 = 61
var num62 = 62
var num63 = 63
var num64 = 64
var num65 = 65
var num66 = 66
var num67 = 67
var num68 = 68
var num69 = 69
var num70 = 70
var num71 = 71
var num72 = 72
var num73 = 73
var num74 = 74
var num75 = 75
var num76 = 76
var num77 = 77
var num78 = 78
var num79 = 79
var num80 = 80
var num81 = 81
var num82 = 82
var num83 = 83
var num84 = 84
var num85 = 85
var num86 = 86
var num87 = 87
var num88 = 88
var num89 = 89
var num90 = 90
var num91 = 91
var num92 = 92
var num93 = 93
var num94 = 94
var num95
var words = sentence.split(by: " ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.split(" ")
for word in words {
var count = 0
for i in 1...word.length {
if word.substring(0, i).isPrime {
count += 1
}
}
if count == 1 {
result += " " + word
}
}
return result.trim()
}
struct PrimeWordsInSentence_swift {
static func main() {
print(wordsInSentence("This is a test"))
print(wordsInSentence("lets go for swimming"))
}
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.split(" ")
for word in words {
var count = 0
for i in 1...word.length {
if word.substring(0, i).isPrime {
count += 1
}
}
if count == 1 {
result += " " + word
}
}
return result.trim()
}
struct PrimeWordsInSentence_swift {
static func main() {
print(wordsInSentence("This is a test"))
print(wordsInSentence("lets go for swimming"))
}
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성현 on 2021/03/18.
//
import Foundation
var num1 = 10
var num2 = 20
var sum = num1 + num2
var sub = num1 - num2
var mul = num1 * num2
var div = num1 / num2
var mod = num1 % num2
print("sum = \(sum)")
print("sub = \(sub)")
print("mul = \(mul)")
print("div = \(div)")
print("mod = \(mod)")
var num3 = 10
var num4 = 20
var sum2 = num3 + num4
var sub2 = num3 - num4
var mul2 = num3 * num4
var div2 = num3 / num4
var mod2 = num3 % num4
print("sum2 = \(sum2)")
print("sub2 = \(sub2)")
print("mul2 = \(mul2)")
print("div2 = \(div2)")
print("mod2 = \(mod2)")<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성현 on 2021/03/18.
//
import Foundation
var num1 = 10
var num2 = 20
var sum = num1 + num2
var sub = num1 - num2
var mul = num1 * num2
var div = num1 / num2
var mod = num1 % num2
print("sum = \(sum)")
print("sub = \(sub)")
print("mul = \(mul)")
print("div = \(div)")
print("mod = \(mod)")
var num3 = 10
var num4 = 20
var sum2 = num3 + num4
var sub2 = num3 - num4
var mul2 = num3 * num4
var div2 = num3 / num4
var mod2 = num3 % num4
print("sum2 = \(sum2)")
print("sub2 = \(sub2)")
print("mul2 = \(mul2)")
print("div2 = \(div2)")
print("mod2 = \(mod2)")<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성현 on 2021/03/18.
//
import Foundation
var num1 = 10
var num2 = 20
var sum = num1 + num2
var sub = num1 - num2
var mul = num1 * num2
var div = num1 / num2
var mod = num1 % num2
print("sum = \(sum)")
print("sub = \(sub)")
print("mul = \(mul)")
print("div = \(div)")
print("mod = \(mod)")
var num3 = 10
var num4 = 20
var sum2 = num3 + num4
var sub2 = num3 - num4
var mul2 = num3 * num4
var div2 = num3 / num
var words = sentence.split(" ") // no exact matches in call to instance method 'split'
return result.trim() // value of type 'String' has no member 'trim'
print(wordsInSentence("This is a test")) // missing argument label 'sentence:' in call
print(wordsInSentence("lets go for swimming")) // missing argument label 'sentence:' in call
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.split(separator: " ")
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 2 {
return true
}
if number % 2 == 0 {
return false
}
for i in 3...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = ""
var words = sentence.split(separator: " ")
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 2 {
return true
}
if number % 2 == 0 {
return false
}
for i in 3...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 장성원 on 2022/01/15.
//
import Foundation
var firstName = "장"
var lastName = "성원"
var fullName = firstName + lastName
print(fullName)
var count = 10
var countString = "\(count)"
print(countString)
var pi = 3.141592653589793
var piString = "\(pi)"
print(piString)
var piString2 = String(pi)
print(piString2)
var piString3 = String(format: "%.2f", value: pi)
print(piString3)
var piString4 = String(format: "%.2f", value: pi)
print(piString4)
var piString5 = String(format: "%.2f", value: pi)
print(piString5)
var piString6 = String(format: "%.2f", value: pi)
print(piString6)
var piString7 = String(format: "%.2f", value: pi)
print(piString7)
var piString8 = String(format: "%.2f", value: pi)
print(piString8)
var piString9 = String(format: "%.2f", value: pi)
print(piString9)
var piString10 = String(format: "%.2f", value: pi)
print(piString10)
var piString11 = String(format: "%.2f", value: pi)
print(piString11)
var piString12 = String(format: "%.2f", value: pi)
print(piString12)
var piString13 = String(format: "%.2f", value: pi)
print(piString13)
var piString14 = String(format: "%.2f", value: pi)
print(piString14)
var piString15 = String(format: "%.2f", value: pi)
print(piString15)
var piString16 = String(format: "%.2f", value: pi)
print(piString16)
var piString17 = String(format: "%.2f", value: pi)
print(piString17)
var piString18 = String(format: "%.2f", value: pi)
print(piString18)
var piString19 = String(format: "%.2f", value: pi)
print(piString19)
var piString20 = String(format: "%.2f", value: pi)
print(piString20)
var piString21 = String(format: "%.2f", value: pi)
print(piString21)
var piString22 = String(format: "%.2f", value: pi)
print(piString22)
var piString23 = String(format: "%.2f", value: pi)
print(piString23)
var piString24 = String(format: "%.2f", value: pi)
print(piString24)
var piString25 = String(format: "%.2f",
if isPrime(word.length) { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if isPrime(word.length) { // missing argument label 'number:' in call
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = ""
for word in words {
let num = Int(word)
if isPrime(num) {
primeWords += word + " "
}
}
return primeWords.trim()
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...num {
if num % i == 0 {
return false
}
}
return true
}
import Cocoa
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var primeWords = ""
for word in words {
let num = Int(word)
if isPrime(num) {
primeWords += word + " "
}
}
return primeWords.trim()
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...num {
if num % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 136. Single Number
//
// Created by yuhua on 2020/11/2.
//
import Cocoa
class Solution:
// 1. 异或运算
// 2. 相同的数字异或为0
// 3. 0异或任何数字都为数字本身
// 4. 任何数字异或0都为数字本身
// 5. 异或运算满足交换律
// 6. 相同的数字异或为0
// 7. 0异或任何数字都为数字本身
// 8. 任何数字异或0都为数字本身
// 9. 异或运算满足交换律
// 10. 相同的数字异或为0
// 11. 0异或任何数字都为数字本身
// 12. 任何数字异或0都为数字本身
// 13. 异或运算满足交换律
// 14. 相同的数字异或为0
// 15. 0异或任何数字都为数字本身
// 16. 任何数字异或0都为数字本身
// 17. 异或运算满足交换律
// 18. 相同的数字异或为0
// 19. 0异或任何数字都为数字本身
// 20. 任何数字异或0都为数字本身
// 21. 异或运算满足交换律
// 22. 相同的数字异或为0
// 23. 0异或任何数字都为数字本身
// 24. 任何数字异或0都为数字本身
// 25. 异或运算满足交换律
// 26. 相同的数字异或为0
// 27. 0异或任何数字都为数字本身
// 28. 任何数字异或0都为数字本身
// 29. 异或运算满足交换律
// 30. 相同的数字异或为0
// 31. 0异或任何数字都为数字本身
// 32. 任何数字异或0都为数字本身
// 33. 异或运算满足交换律
// 34. 相同的数字异或为0
// 35. 0异或任何数字都为数字本身
// 36. 任何数字异或0都为数字本身
// 37. 异或运算满足交换律
// 38. 相同的数字异或为0
// 39. 0异或任何数字都为数字本身
// 40. 任何数字异或0都为数字本身
// 41. 异或运算满足交换律
// 42. 相同的数字异或为0
// 43. 0异或任何数字都为数字本身
// 44. 任何数字异或0都为数字本身
// 45. 异或运算满足交换律
// 46. 相同的数字异或为0
// 47. 0异或任何数字都为数字本身
// 48. 任何数字异或0都为数字本身
// 49. 异或运算满足交换律
// 50. 相同的数字异或为0
// 51. 0异或任何数字都为数字本身
// 52. 任何数字异或0都为数字本身
// 53. 异或运算满足交换律
// 54. 相同的数字异或为0
// 5
if isPrime(num) { // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if isPrime(num) { // missing argument label 'num:' in call
return primeWords.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 2 {
return true
}
if number % 2 == 0 {
return false
}
for i in 3..<number {
if number % i == 0 {
return false
}
}
return true
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number == 2 {
return true
}
if number % 2 == 0 {
return false
}
for i in 3..<number {
if number % i == 0 {
return false
}
}
return true
}<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
sum += i
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
sum += i
}
}
print(sum)<|endoftext|>//
// main.swift
// 100DaysOfSwift
//
// Created by 임성동 on 2022/05/17.
//
import Foundation
var num = 100
var sum = 0
for i in 1...num {
if i % 2 == 0 {
if isPrime(word.length) { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if isPrime(word.length) { // missing argument label 'number:' in call
return result.trim() // value of type 'String' has no member 'trim'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2...number {
if number % i == 0 {
return i == number
}
}
return true
}
import Foundation
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(word.length) {
result += word + " "
}
}
return result.trim()
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
for i in 2...number {
if number % i == 0 {
return i == number
}
}
return true
}<|endoftext|>//
// main.swift
// 100DaysOfCode
//
// Created by 최선호 on 2021/07/07.
//
import Foundation
// 1. 함수
// 1.1 함수 선언
// 1.1.1 함수 선언 방법 1
// 1.1.2 함수 선언 방법 2
// 1.2 함수 호출
// 1.3 함수 입력 및 반환
// 1.4 함수 입력 및 반환 예제
// 1.5 함수 입력 및 반환 예제 2
// 1.6 함수 입력 및 반환 예제 3
// 1.7 함수 입력 및 반환 예제 4
// 1.8 함수 입력 및 반환 예제 5
// 1.9 함수 입력 및 반환 예제 6
// 1.10 함수 입력 및 반환 예제 7
// 1.11 함수 입력 및 반환 예제 8
// 1.12 함수 입력 및 반환 예제 9
// 1.13 함수 입력 및 반환 예제 10
// 1.14 함수 입력 및 반환 예제 11
// 1.15 함수 입력 및 반환 예제 12
// 1.16 함수 입력 및 반환 예제 13
// 1.17 함수 입력 및 반환 예제 14
// 1.18 함수 입력 및 반환 예제 15
// 1.19 함수 입력 및 반환 예제 16
// 1.20 함수 입력 및 반환 예제 17
// 1.21 함수 입력 및 반환 �����
if isPrime(word.length) { // value of type 'String.SubSequence' (aka 'Substring') has no member 'length'
if isPrime(word.length) { // missing argument label 'number:' in call
return result.trim() // value of type 'String' has no member 'trim'
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
return xFraction.multiply(nFraction).isWholeNumber()
}
struct Fraction {
var numerator: Int
var denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
func multiply(other: Fraction) -> Fraction {
return Fraction(numerator: numerator * other.numerator, denominator: denominator * other.denominator)
}
func isWholeNumber() -> Bool {
return numerator % denominator == 0
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
return xFraction.multiply(nFraction).isWholeNumber()
}
struct Fraction {
var numerator: Int
var denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
func multiply(other: Fraction) -> Fraction {
return Fraction(numerator: numerator * other.numerator, denominator: denominator * other.denominator)
}
func isWholeNumber() -> Bool {
return numerator % denominator == 0
}
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------
let xFraction = Fraction(x) // missing argument for parameter 'denominator' in call
let xFraction = Fraction(x) // cannot convert value of type 'String' to expected argument type 'Int'
let xFraction = Fraction(x) // missing argument label 'numerator:' in call
let nFraction = Fraction(n) // missing argument for parameter 'denominator' in call
let nFraction = Fraction(n) // missing argument label 'numerator:' in call
let nFraction = Fraction(n) // cannot convert value of type 'String' to expected argument type 'Int'
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
return xFraction.multiply(nFraction).isWholeNumber()
}
struct Fraction {
let numerator: Int
let denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
func multiply(other: Fraction) -> Fraction {
return Fraction(
numerator: numerator * other.numerator,
denominator: denominator * other.denominator
)
}
func isWholeNumber() -> Bool {
return numerator % denominator == 0
}
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
return xFraction.multiply(nFraction).isWholeNumber()
}
struct Fraction {
let numerator: Int
let denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
func multiply(other: Fraction) -> Fraction {
return Fraction(
numerator: numerator * other.numerator,
denominator: denominator * other.denominator
)
}
func isWholeNumber() -> Bool {
return numerator % denominator == 0
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let xFraction = Fraction(x) // missing argument for parameter 'denominator' in call
let xFraction = Fraction(x) // cannot convert value of type 'String' to expected argument type 'Int'
let xFraction = Fraction(x) // missing argument label 'numerator:' in call
let nFraction = Fraction(n) // missing argument for parameter 'denominator' in call
let nFraction = Fraction(n) // missing argument label 'numerator:' in call
let nFraction = Fraction(n) // cannot convert value of type 'String' to expected argument type 'Int'
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xy = xNum * nDen
let yx = nNum * xDen
let gcd = gcd(xy, yx)
return xy / gcd == yx / gcd
}
func gcd(xy: Int, yx: Int) -> Int {
while yx != 0 {
let temp = yx
yx = xy % yx
xy = temp
}
return xy
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xy = xNum * nDen
let yx = nNum * xDen
let gcd = gcd(xy, yx)
return xy / gcd == yx / gcd
}
func gcd(xy: Int, yx: Int) -> Int {
while yx != 0 {
let temp = yx
yx = xy % yx
xy = temp
}
return xy
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------
let gcd = gcd(xy, yx) // missing argument labels 'xy:yx:' in call
yx = xy % yx // cannot assign to value: 'yx' is a 'let' constant
xy = temp // cannot assign to value: 'xy' is a 'let' constant
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])
let xDen = Int(xArr[1])
let nNum = Int(nArr[0])
let nDen = Int(nArr[1])
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])
let xDen = Int(xArr[1])
let nNum = Int(nArr[0])
let nDen = Int(nArr[1])
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
let x = "1/5"
let n = "5/1"
print(simplify(x: x, n: n))
let x1 = "1/6"
let n1 = "2/1"
print(simplify(x: x1, n: n1))
let x2 = "7/10"
let n2 = "10/2"
print(simplify(x: x2, n: n2))
let x3 = "1/2"
let n3 = "2/1"
print(simplify(x: x3, n: n3))
let x4 = "1/2"
let n4 = "2/1"
print(simplify(x: x4, n: n4))
let x5 = "1/2"
let n5 = "2/2"
print(simplify(x: x5, n: n5))
let x6 = "1/2"
let n6 = "2/3"
print(simplify(x: x6, n: n6))
let x7 = "1/2"
let n7 = "3/2"
print(simplify(x: x7, n: n7))
let x8 = "1/2"
let n8 = "3/3"
print(simplify(x: x8, n: n8))
let x9 = "1/2"
let n9 = "3/4"
print(simplify(x: x9, n: n9))
let x10 = "1/2"
let n10 = "4/3"
print(simplify(x: x10, n: n10))
let x11 = "1/2"
let n11 = "4/4"
print(simplify(x: x11, n: n11))
let x12 = "1/2"
let n12 = "4/5"
print(simplify(x: x12, n: n12))
let x13 = "1/2"
let n13 = "5/4"
print(simplify(x: x13, n: n13))
let x14 = "1/2"
let n14 = "5/5"
print(simplify(x: x14, n: n14))
let x15 = "1/2"
let n15 = "5/6"
print(simplify(x: x15, n: n15))
let x16 = "1/2"
let n16 = "6/5"
print(simplify(x: x16, n: n16))
let x17 = "1/2"
let n17 = "6/6"
print(simplify(x: x17, n: n17))
let x18 = "1/2"
let n18 = "6/7"
print(simplify(x: x18, n: n18))
let x19 = "1/2"
let n19 = "7/6"
print(simplify(x: x19, n: n19))
let x20 = "1/2"
let n20 = "7/7"
print(simplify(x: x20, n: n20))
let x21 = "1/2"
let n21 = "7/8"
print(simplify(x: x21, n: n21))
let x22 = "1/2"
let n22 = "8/7"
print(simplify(x: x22, n
let xy = xNum * nDen // binary operator '*' cannot be applied to two 'Int?' operands
let yx = nNum * xDen // binary operator '*' cannot be applied to two 'Int?' operands
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
let product = xFraction * nFraction
return product.isWholeNumber
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xFraction = Fraction(x)
let nFraction = Fraction(n)
let product = xFraction * nFraction
return product.isWholeNumber
}
struct Fraction {
let numerator: Int
let denominator: Int
init(numerator: Int, denominator: Int) {
self.numerator = numerator
self.denominator = denominator
}
var isWholeNumber: Bool {
return numerator % denominator == 0
}
var asWholeNumber: Int {
return numerator / denominator
}
var asDecimal: Float {
return Float(numerator) / Float(denominator)
}
func asString() -> String {
return "\(numerator)/\(denominator)"
}
func asFraction() -> Fraction {
return Fraction(numerator: numerator, denominator: denominator)
}
func asDecimalString() -> String {
return "\(asDecimal)"
}
func asFractionString() -> String {
return asString()
}
func asFractionString(precision: Int) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision)
return "\(roundedDecimal)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal) \(roundingModeString)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String, roundingModeString2: String) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal) \(roundingModeString) \(roundingModeString2)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String, roundingModeString2: String, roundingModeString3: String) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal) \(roundingModeString) \(roundingModeString2) \(roundingModeString3)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String, roundingModeString2: String, roundingModeString3: String, roundingModeString4: String) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal) \(roundingModeString) \(roundingModeString2) \(roundingModeString3) \(roundingModeString4)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String, roundingModeString2: String, roundingModeString3: String, roundingModeString4: String, roundingModeString5: String) -> String {
let decimal = asDecimal
let roundedDecimal = round(decimal, to: precision, roundingMode: roundingMode)
return "\(roundedDecimal) \(roundingModeString) \(roundingModeString2) \(roundingModeString3) \(roundingModeString4) \(roundingModeString5)"
}
func asFractionString(precision: Int, roundingMode: RoundingMode, roundingModeString: String, roundingModeString2: String, roundingModeString3: String, roundingModeString4: String, roundingModeString5: String, roundingModeString6
let xFraction = Fraction(x) // cannot find 'Fraction' in scope
let nFraction = Fraction(n) // cannot find 'Fraction' in scope
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map { Int(String($0))! }
let nArr = n.split(separator: "/").map { Int(String($0))! }
let xNum = xArr[0] * nArr[1]
let nNum = xArr[1] * nArr[0]
return xNum == nNum
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map { Int(String($0))! }
let nArr = n.split(separator: "/").map { Int(String($0))! }
let xNum = xArr[0] * nArr[1]
let nNum = xArr[1] * nArr[0]
return xNum == nNum
}
var x = "1/5"
var n = "5/1"
print(simplify(x: x, n: n))
x = "1/6"
n = "2/1"
print(simplify(x: x, n: n))
x = "7/10"
n = "10/2"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1/10"
n = "10/1"
print(simplify(x: x, n: n))
x = "1
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xArray = x.split(separator: "/").map(String.init)
let nArray = n.split(separator: "/").map(String.init)
let xNum = Int(xArray[0])
let xDen = Int(xArray[1])
let nNum = Int(nArray[0])
let nDen = Int(nArray[1])
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArray = x.split(separator: "/").map(String.init)
let nArray = n.split(separator: "/").map(String.init)
let xNum = Int(xArray[0])
let xDen = Int(xArray[1])
let nNum = Int(nArray[0])
let nDen = Int(nArray[1])
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
// 2.
// Given a string of text, return the most common letter in the text.
// If there are more than one letter with the same frequency, return the one that appears first in the text.
// Example:
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!") == "l"
// mostCommonLetter("Hello World!"
let xy = xNum * nDen // binary operator '*' cannot be applied to two 'Int?' operands
let yx = nNum * xDen // binary operator '*' cannot be applied to two 'Int?' operands
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xNumDen = xNum * nDen
let nNumDen = nNum * xDen
return xNumDen == nNumDen
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xNumDen = xNum * nDen
let nNumDen = nNum * xDen
return xNumDen == nNumDen
}
var result = simplify(x: "1/5", n: "5/1")
print("result: \(result)")
result = simplify(x: "1/6", n: "2/1")
print("result: \(result)")
result = simplify(x: "7/10", n: "10/2")
print("result: \(result)")
result = simplify(x: "1/1", n: "1/1")
print("result: \(result)")
result = simplify(x: "1/2", n: "1/2")
print("result: \(result)")
result = simplify(x: "1/3", n: "1/3")
print("result: \(result)")
result = simplify(x: "1/4", n: "1/4")
print("result: \(result)")
result = simplify(x: "1/5", n: "1/5")
print("result: \(result)")
result = simplify(x: "1/6", n: "1/6")
print("result: \(result)")
result = simplify(x: "1/7", n: "1/7")
print("result: \(result)")
result = simplify(x: "1/8", n: "1/8")
print("result: \(result)")
result = simplify(x: "1/9", n: "1/9")
print("result: \(result)")
result = simplify(x: "1/10", n: "1/10")
print("result: \(result)")
result = simplify(x: "1/11", n: "1/11")
print("result: \(result)")
result = simplify(x: "1/12", n: "1/12")
print("result: \(result)")
result = simplify(x: "1/13", n: "1/13")
print("result: \(result)")
result = simplify(x: "1/14", n: "1/14")
print("result: \(result)")
result = simplify(x: "1/15", n: "1/15")
print("result: \(result)")
result = simplify(x: "1/16", n: "1/16")
print("result: \(result)")
result = simplify(x: "1/17", n: "1/17")
print("result: \(result)")
result = simplify(x: "1/18", n: "1/18")
print("result: \(result)")
result = simplify(x: "1/19", n: "1/19")
print("result: \(result)")
result = simplify(x: "1/20", n: "1/20")
print("result: \(result)")
result = simplify(x: "1/21", n: "1/21")
print("result: \(result)")
result = simplify(x: "1/22", n: "1/22")
print("result: \(result)")
result = simplify(x: "1/23", n: "1/23")
print("result: \(result)"
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map { Int($0) }
let nArr = n.split(separator: "/").map { Int($0) }
let xNum = xArr[0] * nArr[1]
let nNum = xArr[1] * nArr[0]
return xNum == nNum
}
func firstUniqChar(s: String) -> Int {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
func lengthOfLongestSubstring(s: String) -> Int {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map { Int($0) }
let nArr = n.split(separator: "/").map { Int($0) }
let xNum = xArr[0] * nArr[1]
let nNum = xArr[1] * nArr[0]
return xNum == nNum
}
// 2.
// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
// Examples:
// s = "leetcode"
// return 0.
// s = "loveleetcode"
// return 2.
// Note: You may assume the string contain only lowercase letters.
func firstUniqChar(s: String) -> Int {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
// 3.
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
// 4.
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
// 5.
// Given a string, find the length of the longest substring without repeating characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
func lengthOfLongestSubstring(s: String) -> Int {
var arr = [Int(Character(c: c).asciiValue) for c in s]
var count = [Int(Character(c: c).asciiValue) for c in s]
for i in arr {
if count[i] == 1 {
return i
}
}
return -1
}
// 6.
// Given a string, find the length of the longest substring without repeating characters.
// Examples:
// Given "abcabcbb", the answer is "abc", which the length is 3.
// Given "bbbbb", the answer is "b", with the length of 1.
// Given "pwwkew", the answer is
let xNum = xArr[0] * nArr[1] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let xNum = xArr[0] * nArr[1] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let nNum = xArr[1] * nArr[0] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let nNum = xArr[1] * nArr[0] // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
var arr = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
var arr = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
var arr = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var count = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
var count = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
var count = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var count = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var count = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var arr = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var arr = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var arr = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
var count = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var count = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var count = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
var count = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var count = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
return -1 // cannot convert return expression of type 'Int' to return type '[Int]'
var arr = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var arr = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var arr = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
var arr = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var count = [Int(Character(c: c).asciiValue) for c in s] // no exact matches in call to initializer
var count = [Int(Character(c: c).asciiValue) for c in s] // expected ',' separator
var count = [Int(Character(c: c).asciiValue) for c in s] // expected expression in container literal
var count = [Int(Character(c: c).asciiValue) for c in s] // value of optional type 'UInt8?' must be unwrapped to a value of type 'UInt8'
var count = [Int(Character(c: c).asciiValue) for c in s] // cannot find 'c' in scope
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let xArr = x.split(separator: "/").map(String.init)
let nArr = n.split(separator: "/").map(String.init)
let xNum = Int(xArr[0])!
let xDen = Int(xArr[1])!
let nNum = Int(nArr[0])!
let nDen = Int(nArr[1])!
let xy = xNum * nDen
let yx = nNum * xDen
return xy == yx
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in 0..<sorted.count {
result.append(sorted[i])
}
return result
}
func countGreater(nums: [Int], target: Int) -> Int {
var count = 0
for i in 0..<nums.count {
if nums[i] > target {
count += 1
}
}
return count
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in 0..<sorted.count {
result.append(sorted[i])
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function which returns the number of elements in the given array
// which are strictly greater than the given element.
// For example:
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 5) == 4
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 10) == 0
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 1) == 9
// countGreater(nums: [] as [Int], target: 1) == 0
func countGreater(nums: [Int], target: Int) -> Int {
var count = 0
for i in 0..<nums.count {
if nums[i] > target {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Write a function which returns the number of elements in the given array
// which are strictly greater than the given element.
// For example:
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 5) == 4
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 10) == 0
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 1) == 9
// countGreater(nums: [] as [Int], target: 1) == 0
func countGreater(nums: [Int], target: Int) -> Int {
var count = 0
for i in 0..<nums.count {
if nums[i] > target {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. Write a function which returns the number of elements in the given array
// which are strictly greater than the given element.
// For example:
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 5) == 4
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 10) == 0
// countGreater(nums: [1, 2, 3, 4, 5, 6, 7, 8, 9], target: 1) == 9
// countGreater(nums: [] as [Int], target: 1) == 0
func countGreater(nums: [Int], target: Int) -> Int {
var count = 0
for i in 0..<nums.count {
if nums[i] > target {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Write a function which returns the number of elements in the given array
// which are strictly greater than the given element.
// For example:
// countGreater(nums: [
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted(by: { $0 < $1 })
return sorted
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted(by: { $0 < $1 })
return sorted
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
return nums.sorted(by: { $0 < $1 })
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
print(orderByPoints(nums: [1, 11, -1, -11, -12]))
print(orderByPoints(nums: [] as [Int]))
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
result.append(i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
var sum = 0
var num = i
while num > 0 {
sum += num % 10
num /= 10
}
result.append(i)
}
return result
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
var sorted = nums.sorted(by: { $0 < $1 })
var result = [Int]()
for i in sorted {
var sum = 0
var num = i
while num > 0 {
sum += num % 10
num /= 10
}
result.append(i)
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
var sorted = nums.sorted(by: { $0 < $1 }) // variable 'sorted' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: {
let firstDigit = Int(String($0).first!)!
let lastDigit = Int(String($0).last!)!
return $0 > 10 && firstDigit % 2 == 1 && lastDigit % 2 == 1
})
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: {
let firstDigit = Int(String($0).first!)!
let lastDigit = Int(String($0).last!)!
return $0 > 10 && firstDigit % 2 == 1 && lastDigit % 2 == 1
})
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
return nums.count(where: { // cannot call value of non-function type 'Int'
let firstDigit = Int(String($0).first!)! // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && ($0 % 10) % 2 == 1 })
}
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).sum()
}
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).reduce(0, { $0 + $1 })
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && ($0 % 10) % 2 == 1 })
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an array of numbers as input and returns
// the sum of all numbers in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 108
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).sum()
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes an array of numbers as input and returns
// the sum of all numbers in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 108
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an array of numbers as input and returns
// the sum of all numbers in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 108
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes an array of numbers as input and returns
// the sum of all numbers in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 108
func specialSum(nums: [Int]) -> Int {
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes an array of numbers as input and returns
// the sum of all numbers in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15])
return nums.count(where: { $0 > 10 && ($0 % 10) % 2 == 1 }) // cannot call value of non-function type 'Int'
return nums.filter({ $0 > 10 && ($0 % 10) % 2 == 1 }).sum() // value of type '[Int]' has no member 'sum'
func specialSum(nums: [Int]) -> Int { // invalid redeclaration of 'specialSum(nums:)'
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
func sumOfSquares(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num * num
}
return sum
}
func sumOfSquaresExcludingFirstAndLast(nums: [Int]) -> Int {
var sum = 0
for num in nums[1..<nums.count-1] {
sum += num * num
}
return sum
}
func sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
nums: [Int]) -> Int {
var sum = 0
var i = 0
while i < nums.count {
sum += nums[i] * nums[i]
i += 1
}
return sum
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && (num % 10) % 2 == 1 && (num / 10) % 2 == 1 {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an array of numbers as input and returns the
// sum of the squares of the numbers in the array.
// For example:
// sumOfSquares(nums: [1, 2, 3]) == 14
// sumOfSquares(nums: [4, 5, 6]) == 130
func sumOfSquares(nums: [Int]) -> Int {
var sum = 0
for num in nums {
sum += num * num
}
return sum
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of numbers as input and returns the
// sum of the squares of the numbers in the array, excluding the first and last
// elements.
// For example:
// sumOfSquaresExcludingFirstAndLast(nums: [1, 2, 3, 4, 5]) == 25
// sumOfSquaresExcludingFirstAndLast(nums: [1, 2, 3, 4, 5, 6]) == 35
func sumOfSquaresExcludingFirstAndLast(nums: [Int]) -> Int {
var sum = 0
for num in nums[1..<nums.count-1] {
sum += num * num
}
return sum
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of numbers as input and returns the
// sum of the squares of the numbers in the array, excluding the first and last
// elements, excluding the first and last elements, excluding the first and last
// elements, etc.
// For example:
// sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
// nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1000
// sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
// nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == 10000
func sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
nums: [Int]) -> Int {
var sum = 0
var i = 0
while i < nums.count {
sum += nums[i] * nums[i]
i += 1
}
return sum
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of numbers as input and returns the
// sum of the squares of the numbers in the array, excluding the first and last
// elements, excluding the first and last elements, excluding the first and last
// elements, etc., excluding the first and last elements, excluding the first and
// last elements, excluding the first and last elements, etc.
// For example:
// sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
// nums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1000
// sumOfSquaresExcludingFirstAndLastExcludingFirstAndLastExcludingFirstAndLast(
// nums: [1, 2, 3, 4, 5, 6, 7, 8, 9
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
func vowelCount(string: String) -> Int {
return string.count(where: \Character.isVowel)
}
func sumArray(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)
}
func longestString(strings: [String]) -> String {
return strings.max(by: \.count)!
}
func average(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)/numbers.count
}
func sumArray(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)/numbers.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// vowelCount("Hello world") == 3
// vowelCount("aeiou") == 5
func vowelCount(string: String) -> Int {
return string.count(where: \Character.isVowel)
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of numbers as input and returns the
// sum of all the numbers in the array.
// For example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, -2, -3, -4, -5]) == -15
func sumArray(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of strings as input and returns the
// longest string in the array.
// For example:
// longestString(["apple", "banana", "cherry"]) == "cherry"
// longestString(["cat", "dog", "elephant"]) == "elephant"
func longestString(strings: [String]) -> String {
return strings.max(by: \.count)!
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of numbers as input and returns the
// average of all the numbers in the array.
// For example:
// average([1, 2, 3, 4, 5]) == 3
// average([-1, -2, -3, -4, -5]) == -3
func average(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)/numbers.count
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// vowelCount("Hello world") == 3
// vowelCount("aeiou") == 5
func vowelCount(string: String) -> Int {
return string.count(where: \Character.isVowel)
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes an array of numbers as input and returns the
// sum of all the numbers in the array.
// For example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, -2, -3, -4, -5]) == -15
func sumArray(numbers: [Int]) -> Int {
return numbers.reduce(0, \+)/numbers.count
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes an array of strings as input and returns the
// longest string in the array.
// For example:
// longestString(["apple", "banana", "cherry"]) == "cherry"
// longestString(["cat", "dog", "elephant"]) == "elephant"
func longestString(strings: [String]) -> String {
return strings.max(by: \.count)!
}
// ---------------------------------------------------------------------
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: {
$0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1
})
}
func vowelCount(s: String) -> Int {
return s.count(where: {
$0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u"
})
}
func sumArray(nums: [Int]) -> Int {
return nums.reduce(0, { $0 + $1 })
}
func longestString(strings: [String]) -> String {
return strings.max(by: { $0.length })!
}
func average(nums: [Int]) -> Int {
return nums.reduce(0, { $0 + $1 }) / nums.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: {
$0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1
})
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// vowelCount("Hello world") == 3
// vowelCount("aeiou") == 5
// vowelCount("") == 0
func vowelCount(s: String) -> Int {
return s.count(where: {
$0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u"
})
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an array of numbers as input and returns the
// sum of all the numbers in the array.
// For example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, -2, -3, -4, -5]) == -15
// sumArray([]) == 0
func sumArray(nums: [Int]) -> Int {
return nums.reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes an array of strings as input and returns the
// longest string in the array.
// For example:
// longestString(["apple", "banana", "cherry"]) == "cherry"
// longestString(["a", "bb", "ccc"]) == "ccc"
// longestString([]) == ""
func longestString(strings: [String]) -> String {
return strings.max(by: { $0.length })!
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an array of numbers as input and returns the
// average of all the numbers in the array.
// For example:
// average([1, 2, 3, 4, 5]) == 3
// average([-1, -2, -3, -4, -5]) == -3
// average([]) == 0
func average(nums: [Int]) -> Int {
return nums.reduce(0, { $0 + $1 }) / nums.count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// vowelCount("Hello world") == 3
// vowelCount("aeiou") == 5
// vowelCount("") == 0
func vowelCount(s: String) -> Int {
return s.count(where: {
$0 == "a" || $0 == "e" || $0 == "i" || $0 == "o" || $0 == "u"
})
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes an array of numbers as input and returns the
// sum of all the numbers in the array.
// For example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, -2, -3, -4, -5]) == -15
// sumArray([]) == 0
func sumArray(nums: [Int]) -> Int {
return nums.reduce(0, { $0 + $1 })
}
// ------------------------------------------------
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1 })
}
func vowelCount(s: String) -> Int {
return s.count(where: { $0.isVowel() })
}
func wordCount(s: String) -> Int {
return s.split(" ").count
}
func vowelWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isVowel() })
}
func consonantWordsCount(s: String) -> Int {
return s.split(" ").count(where: { !$0.isVowel() })
}
func digitWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isDigit() })
}
func letterWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isLetter() })
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1 })
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// vowelCount("Hello World") == 3
// vowelCount("aeiou") == 5
// vowelCount("") == 0
func vowelCount(s: String) -> Int {
return s.count(where: { $0.isVowel() })
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the number of
// words in the string.
// For example:
// wordCount("Hello World") == 2
// wordCount("Hello World, how are you?") == 4
// wordCount("") == 0
func wordCount(s: String) -> Int {
return s.split(" ").count
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the number of
// words in the string that start with a vowel.
// For example:
// vowelWordsCount("Hello World") == 1
// vowelWordsCount("Hello World, how are you?") == 2
// vowelWordsCount("") == 0
func vowelWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isVowel() })
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the number of
// words in the string that start with a consonant.
// For example:
// consonantWordsCount("Hello World") == 1
// consonantWordsCount("Hello World, how are you?") == 2
// consonantWordsCount("") == 0
func consonantWordsCount(s: String) -> Int {
return s.split(" ").count(where: { !$0.isVowel() })
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the number of
// words in the string that contain only digits.
// For example:
// digitWordsCount("Hello World") == 0
// digitWordsCount("Hello World, how are you?") == 1
// digitWordsCount("") == 0
func digitWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isDigit() })
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the number of
// words in the string that contain only letters.
// For example:
// letterWordsCount("Hello World") == 2
// letterWordsCount("Hello World, how are you?") == 4
// letterWordsCount("") == 0
func letterWordsCount(s: String) -> Int {
return s.split(" ").count(where: { $0.isLetter() })
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the number of
// words in the string that contain only letters and digits.
// For example:
// letterAndDigitWordsCount("Hello World") ==
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
func specialSum(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }) * nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// 2. Write a function that takes an array of numbers as input and returns the
// sum of all elements that are greater than 10 and both first and last digits
// of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 109
func specialSum(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }) * nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// 3. Write a function that takes an array of numbers as input and returns the
// sum of all elements that are greater than 10 and both first and last digits
// of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 109
func specialSum(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }) * nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// 4. Write a function that takes an array of numbers as input and returns the
// sum of all elements that are greater than 10 and both first and last digits
// of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 109
func specialSum(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }) * nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// 5. Write a function that takes an array of numbers as input and returns the
// sum of all elements that are greater than 10 and both first and last digits
// of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialSum(nums: [15, -73, 14, -15]) == 1
// specialSum(nums: [33, -2, -3, 45, 21, 109]) == 109
func specialSum(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }) * nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// 6. Write a function that takes an array of
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
func countVowels(s: String) -> Int {
return s.count(where: { $0.isVowel })
}
func countWords(s: String) -> Int {
return s.trim().split(separator: " ").count
}
func countUppercase(s: String) -> Int {
return s.count(where: { $0.isUpper })
}
func countLowercase(s: String) -> Int {
return s.count(where: { $0.isLower })
}
func countDigits(s: String) -> Int {
return s.count(where: { $0.isDigit })
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
func countVowels(s: String) -> Int {
return s.count(where: { $0.isVowel })
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the number of
// words in the string.
// For example:
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
// countWords("") == 0
// countWords(" ") == 0
func countWords(s: String) -> Int {
return s.trim().split(separator: " ").count
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input and returns the number of
// uppercase letters in the string.
// For example:
// countUppercase("Hello world") == 2
// countUppercase("Hello World") == 2
// countUppercase("") == 0
// countUppercase(" ") == 0
func countUppercase(s: String) -> Int {
return s.count(where: { $0.isUpper })
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the number of
// lowercase letters in the string.
// For example:
// countLowercase("Hello world") == 5
// countLowercase("Hello World") == 5
// countLowercase("") == 0
// countLowercase(" ") == 0
func countLowercase(s: String) -> Int {
return s.count(where: { $0.isLower })
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the number of
// digits in the string.
// For example:
// countDigits("Hello world") == 0
// countDigits("Hello World") == 0
// countDigits("") == 0
// countDigits(" ") == 0
// countDigits("12345") == 5
// countDigits("1234567890") == 10
func countDigits(s: String) -> Int {
return s.count(where: { $0.isDigit })
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the number of
// vowels in the string.
// For example:
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
// countVowels(" ") == 0
// countVowels("12345") == 0
// countVowels("1234567890") == 0
func countVowels(s: String) -> Int {
return s.count(where: { $0.isVowel })
}
// ------------------------------
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
func squareSum(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.sum
}
func squareSumGreaterThan10(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.filter { $0 > 10 }.sum
}
func squareSumGreaterThan10AndOddDigits(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.filter { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }.sum
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 })
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes an array of numbers as input and returns
// the sum of the squares of all numbers in the array.
// For example:
// squareSum([2, 3, 4]) == 29
func squareSum(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.sum
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an array of numbers as input and returns
// the sum of the squares of all numbers in the array that are greater than 10.
// For example:
// squareSumGreaterThan10([2, 3, 4]) == 29
// squareSumGreaterThan10([12, 3, 4]) == 100
func squareSumGreaterThan10(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.filter { $0 > 10 }.sum
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes an array of numbers as input and returns
// the sum of the squares of all numbers in the array that are greater than 10
// and both first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// squareSumGreaterThan10AndOddDigits([2, 3, 4]) == 29
// squareSumGreaterThan10AndOddDigits([12, 3, 4]) == 100
// squareSumGreaterThan10AndOddDigits([123, 34, 56]) == 100
func squareSumGreaterThan10AndOddDigits(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.filter { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }.sum
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes an array of numbers as input and returns
// the sum of the squares of all numbers in the array that are greater than 10
// and both first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// squareSumGreaterThan10AndOddDigits([2, 3, 4]) == 29
// squareSumGreaterThan10AndOddDigits([12, 3, 4]) == 100
// squareSumGreaterThan10AndOddDigits([123, 34, 56]) == 100
// squareSumGreaterThan10AndOddDigits([123, 34, 56, 78]) == 100
func squareSumGreaterThan10AndOddDigits(nums: [Int]) -> Int {
return nums.map { $0 * $0 }.filter { $0 > 10 && $0.digits.first! % 2 == 1 && $0.digits.last! % 2 == 1 }.sum
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes an array of numbers as input and returns
// the sum of the squares of all numbers in the array that are greater than 10
// and both first and last digits of a number are odd (1, 3, 5, 7,
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1 })
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.count(where: { $0 > 10 && $0.digits().first! % 2 == 1 && $0.digits().last! % 2 == 1 })
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i + j + k == n {
count += 1
}
}
}
}
return count
}
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
if i + j + k + l == n {
count += 1
}
}
}
}
}
return count
}
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
for m in 1...n {
if i + j + k + l + m == n {
count += 1
}
}
}
}
}
}
return count
}
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
for m in 1...n {
for p in 1...n {
if i + j + k + l + m + p == n {
count += 1
}
}
}
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2.
// Given an integer n, return the number of distinct solutions to the equation
// x1 + x2 + x3 = n, where 1 <= x1, x2, x3 <= n.
// Example :
// Explanation:
// getDistinctSolutions(n: 5) == 2
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i + j + k == n {
count += 1
}
}
}
}
return count
}
// 3.
// Given an integer n, return the number of distinct solutions to the equation
// x1 + x2 + x3 + x4 = n, where 1 <= x1, x2, x3, x4 <= n.
// Example :
// Explanation:
// getDistinctSolutions(n: 5) == 1
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
if i + j + k + l == n {
count += 1
}
}
}
}
}
return count
}
// 4.
// Given an integer n, return the number of distinct solutions to the equation
// x1 + x2 + x3 + x4 + x5 = n, where 1 <= x1, x2, x3, x4, x5 <= n.
// Example :
// Explanation:
// getDistinctSolutions(n: 5) == 1
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
for m in 1...n {
if i + j + k + l + m == n {
count += 1
}
}
}
}
}
}
return count
}
// 5.
// Given an integer n, return the number of distinct solutions to the equation
// x1 + x2 + x3 + x4 + x5 + x6 = n, where 1 <= x1, x2, x3, x4, x5, x6 <= n.
// Example :
// Explanation:
// getDistinctSolutions(n: 5) == 1
func getDistinctSolutions(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
for l in 1...n {
for m in 1...n {
for p in 1...n {
if i + j + k + l + m + p == n {
count += 1
}
}
}
}
}
}
}
return count
}
// 6.
// Given an integer n, return the number of distinct solutions to the equation
// x1 + x2 + x3 + x4 + x5 + x6 + x7 = n, where 1 <= x1, x2, x3, x4, x5, x6, x7 <= n.
// Example :
//
func getDistinctSolutions(n: Int) -> Int { // invalid redeclaration of 'getDistinctSolutions(n:)'
func getDistinctSolutions(n: Int) -> Int { // invalid redeclaration of 'getDistinctSolutions(n:)'
func getDistinctSolutions(n: Int) -> Int { // invalid redeclaration of 'getDistinctSolutions(n:)'
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
func getArithmeticSequenceCount(nums: [Int]) -> Int {
var count = 0
var dp = [Int].init(repeating: 0, count: 1001)
for num in nums {
for i in 1...num {
dp[i] += dp[i - 1]
}
count += dp[num]
}
return count
}
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1, count: nums.count)
var max = 1
for i in 1..<nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 11. Given an integer array nums, return the number of all the arithmetic subsequences of nums.
// A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
// For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.
// For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.
// A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
// For example, [2,5,10] is a subsequence of [1,2,1,2,4,10].
// The answer to the above question is 7.
// Example :
// Explanation:
// nums = [2,4,6,8,10]
// All arithmetic subsequence forms are:
// [2,4,6]
// [4,6,8]
// [6,8,10]
// [2,4,6,8]
// [4,6,8,10]
// getArithmeticSequenceCount(nums: [2,4,6,8,10]) == 7
func getArithmeticSequenceCount(nums: [Int]) -> Int {
var count = 0
var dp = [Int].init(repeating: 0, count: 1001)
for num in nums {
for i in 1...num {
dp[i] += dp[i - 1]
}
count += dp[num]
}
return count
}
// 12. Given an integer array nums, return the number of longest increasing subsequences.
// Notice that the sequence has to be strictly increasing.
// Example :
// Explanation:
// nums = [1,3,5,4,7]
// All the increasing subsequences of nums are:
// [1, 3, 5]
// [1, 3, 4]
// [1, 3, 7]
// [1, 5, 7]
// [3, 5, 7]
// Return 4.
// getNumberOfLIS(nums: [1,3,5,4,7]) == 4
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1, count: nums.count)
var max = 1
for i in 1..<nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
// 13. Given an integer array nums, return the length of the longest strictly increasing subsequence.
// A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
// For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
// Example :
// Explanation:
// nums = [10,9,2,5,3,7,101,18]
// The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
// getLengthOfLIS(nums: [10,9,2,5,3,7,101,18])
dp[i] = max(dp[i], dp[j] + 1) // cannot call value of non-function type 'Int'
max = max(max, dp[i]) // cannot call value of non-function type 'Int'
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1)
var max = 1
for i in 1...nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2.
// Given an integer array nums, return the number of longest increasing subsequences.
// Example :
// Explanation:
// nums = [1, 3, 5, 4, 7]
// LIS = [1, 3, 4, 7]
// There are 3 longest increasing subsequences: [1, 3, 4], [1, 3, 5] and [1, 3, 4, 7].
// getNumberOfLIS(nums: [1, 3, 5, 4, 7]) == 3
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1)
var max = 1
for i in 1...nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
// 3.
// Given an integer array nums, return the number of longest increasing subsequences.
// Example :
// Explanation:
// nums = [1, 3, 5, 4, 7]
// LIS = [1, 3, 4, 7]
// There are 3 longest increasing subsequences: [1, 3, 4], [1, 3, 5] and [1, 3, 4, 7].
// getNumberOfLIS(nums: [1, 3, 5, 4, 7]) == 3
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1)
var max = 1
for i in 1...nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
// 4.
// Given an integer array nums, return the number of longest increasing subsequences.
// Example :
// Explanation:
// nums = [1, 3, 5, 4, 7]
// LIS = [1, 3, 4, 7]
// There are 3 longest increasing subsequences: [1, 3, 4], [1, 3, 5] and [1, 3, 4, 7].
// getNumberOfLIS(nums: [1, 3, 5, 4, 7]) == 3
func getNumberOfLIS(nums: [Int]) -> Int {
var dp = [Int].init(repeating: 1)
var max = 1
for i in 1...nums.count {
for j in 0..<i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
max = max(max, dp[i])
}
return max
}
// 5.
// Given an integer array nums, return the number of longest increasing subsequences.
// Example :
// Explanation:
// nums = [1, 3, 5, 4, 7]
// LIS = [1, 3, 4, 7]
// There are 3 longest increasing subsequences: [1, 3, 4], [1, 3, 5] and [1
var dp = [Int].init(repeating: 1) // missing argument for parameter 'count' in call
dp[i] = max(dp[i], dp[j] + 1) // cannot call value of non-function type 'Int'
max = max(max, dp[i]) // cannot call value of non-function type 'Int'
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in i..<n {
for k in j..<n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in i..<n {
for k in j..<n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1..<n {
for j in i..<n {
for k in j..<n {
if (i * i - i + 1 + j * j - j + 1 + k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
func getGoodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] == nums[j] && i < j {
count += 1
}
}
}
return count
}
func getCountElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] < nums[j] && nums[j] < nums[i] {
count += 1
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1..<n {
for j in i..<n {
for k in j..<n {
if (i * i - i + 1 + j * j - j + 1 + k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 10. Given an array of integers nums, return the number of good pairs.
// A pair (i, j) is called good if nums[i] == nums[j] and i < j.
// Example :
// Explanation: 1, 2, 3, 1, 2, 3 is an array of 6 elements.
// It is good because 1 == 1, 2 == 2, 3 == 3, 1 < 2, 2 < 3, 1 < 3.
// getGoodPairs(nums: [1, 2, 3, 1, 2, 3]) == 3
func getGoodPairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] == nums[j] && i < j {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 11. Given an integer array nums, return the number of elements that have both a
// strictly smaller and a strictly greater element appear in nums.
// Example :
// Explanation: The element 3 has both a strictly smaller element (2) and a
// strictly greater element (4).
// getCountElements(nums: [3, 2, 1, 4]) == 3
func getCountElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] < nums[j] && nums[j] < nums[i] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 12. Given an integer array nums, return the number of elements that have both a
// strictly smaller and a strictly greater element appear in nums.
// Example :
// Explanation: The element 3 has both a strictly smaller element (2) and a
// strictly greater element (4).
// getCountElements(nums: [3, 2, 1, 4]) == 3
func getCountElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] < nums[j] && nums[j] < nums[i] {
count += 1
}
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Given an integer array nums, return the number of elements that have both a
// strictly smaller and a strictly greater element appear in nums.
// Example :
// Explanation: The element 3 has both a strictly smaller element (2) and a
// strictly greater element (4).
// getCountElements(nums: [3, 2, 1, 4]) == 3
func getCountElements(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i..<nums.count {
if nums[i] < nums[j] && nums[j] < nums
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i...n {
for k in j...n {
if (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i...n {
for k in j...n {
if (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 10. Given an integer array nums, return the number of all the triplets [nums[i], nums[j], nums[k]]
// such that i < j < k and nums[i] + nums[j] + nums[k] == 0.
// Notice that the solution set must not contain duplicate triplets.
// Example :
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// Explanation:
// nums = [-1, 0
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in i+1..<n {
for k in j+1..<n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
func getTriplets(nums: [Int]) -> Int {
var result = 0
var numsSorted = nums.sorted()
for i in 0..<nums.count-2 {
var left = i+1
var right = nums.count-1
while left < right {
var sum = numsSorted[i] + numsSorted[left] + numsSorted[right]
if sum == 0 {
result += 1
left += 1
right -= 1
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return result
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var result = 0
for i in 1..<n {
for j in i+1..<n {
for k in j+1..<n {
if (i + j + k) % 3 == 0 {
result += 1
}
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Given an integer array nums, return the number of all the triplets [nums[i], nums[j], nums[k]]
// such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
// Notice that the solution set must not contain duplicate triplets.
// Example :
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
// getTriplets(nums: [-1, 0, 1, 2, -1, -4]) == 2
func getTriplets(nums: [Int]) -> Int {
var result = 0
var numsSorted = nums.sorted()
for i in 0..<nums.count-2 {
var left = i+1
var right = nums.count-1
while left < right {
var sum = numsSorted[i] + numsSorted[left] + numsSorted[right]
if sum == 0 {
result += 1
left += 1
right -= 1
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Given an integer array nums, return the number of all the triplets [nums[i], nums[j], nums[k]]
// such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
// Notice that the solution set must not contain duplicate triplets.
// Example :
// Explanation:
// nums = [-1, 0, 1, 2, -1, -4]
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
// getTriplets(nums: [-1, 0, 1, 2, -1, -4]) == 2
func getTriplets(nums: [Int]) -> Int {
var result = 0
var numsSorted = nums.sorted()
for i in 0..<nums.count-2 {
var left = i+1
var right = nums.count-1
while left < right {
var sum = numsSorted[i] + numsSorted[left] + numsSorted[right]
if sum == 0 {
result += 1
left += 1
right -= 1
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Given an integer array nums, return the number of all the triplets [nums[i], nums[j], nums[k]]
// such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
// Notice that the solution set must not contain duplicate triplets.
// Example
var numsSorted = nums.sorted() // variable 'numsSorted' was never mutated; consider changing to 'let' constant
var sum = numsSorted[i] + numsSorted[left] + numsSorted[right] // variable 'sum' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i + j + k) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j < k && (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) % 3 == 0 {
count += 1
}
}
}
}
return count
}
// 2022-03-29
// 시간 초과
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in 1...n {
for k in 1...n {
if i < j && j <
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i...n {
for k in j...n {
if (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) == 3 * 1000000000 {
count += 1
}
}
}
}
return count
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var count = 0
for i in 1...n {
for j in i...n {
for k in j...n {
if (i * i - i + 1) + (j * j - j + 1) + (k * k - k + 1) == 3 * 1000000000 {
count += 1
}
}
}
}
return count
}
// 2.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example :
// Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
// 3.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example :
// Explanation: There are 2 reverse pairs: (0, 1) and (0, 2).
// So return 2.
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
// 4.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example :
// Explanation: There are 2 reverse pairs: (0, 1) and (0, 2).
// So return 2.
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
// 5.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example :
// Explanation: There are 2 reverse pairs: (0, 1) and (0, 2).
// So return 2.
func reversePairs(nums: [Int]) -> Int {
var count = 0
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] > 2 * nums[j] {
count += 1
}
}
}
return count
}
// 6.
// Given an integer array nums, return the number of reverse pairs in the array.
// A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
// Example :
// Explanation: There are 2 reverse pairs: (0, 1) and (0, 2).
// So return 2.
func reverse
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sorted {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sorted {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
var result = lst.sorted(by: { (lhs, rhs) -> Bool in
if lhs.count == rhs.count {
return lhs < rhs
} else {
return lhs.count < rhs.count
}
})
var result = lst.sorted(by: { (lhs, rhs) -> Bool in
if lhs.count == rhs.count {
return lhs < rhs
} else {
return lhs.count < rhs.count
}
})
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst.sorted(by: { (lhs, rhs) -> Bool in
if lhs.count == rhs.count {
return lhs < rhs
} else {
return lhs.count < rhs.count
}
})
var result = lst.sorted(by: { (lhs, rhs) -> Bool in
if lhs.count == rhs.count {
return lhs < rhs
} else {
return lhs.count < rhs.count
}
})
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
var result = lst.sorted(by: { (lhs, rhs) -> Bool in // invalid redeclaration of 'result'
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sortedList {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sortedList {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
var sortedList = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var sortedList = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sortedList = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 }
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 }
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // value of type 'String' has no member 'length'
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // cannot find operator '<=>' in scope
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // value of type 'String' has no member 'length'
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sorted {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for word in sorted {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sorted = lst.sorted(by: { $0.length <=> $1.length })
var result = []
for i in sorted {
if i.length % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // value of type 'String' has no member 'length'
var sorted = lst.sorted(by: { $0.length <=> $1.length }) // cannot find operator '<=>' in scope
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { (lhs: String, rhs: String) -> Bool in
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length
})
var result = []
for word in sortedList {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var sortedList = lst.sorted(by: { (lhs: String, rhs: String) -> Bool in
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length
})
var result = []
for word in sortedList {
if word.length % 2 == 0 {
result.append(word)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length // value of type 'String' has no member 'length'
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length // value of type 'String' has no member 'length'
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length // value of type 'String' has no member 'length'
return lhs.length == rhs.length ? lhs < rhs : lhs.length < rhs.length // value of type 'String' has no member 'length'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[String]'
func sortedListSum(lst: [String]) -> [String] {
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 }
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 }
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // value of type 'String' has no member 'length'
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // cannot find operator '<=>' in scope
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // value of type 'String' has no member 'length'
return lst.sorted(by: { $0.length <=> $1.length }).filter { $0.length % 2 == 0 } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
func lengthOfString(string: String) -> Int {
return string.count
}
func countVowels(string: String) -> Int {
let vowels = "aeiouAEIOU"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper {
count += 1
}
}
return count
}
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char.isLower {
count += 1
}
}
return count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as an argument and returns the
// length of the string.
// Examples:
// lengthOfString("Hello") == 5
// lengthOfString("") == 0
func lengthOfString(string: String) -> Int {
return string.count
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as an argument and returns the
// number of vowels in the string.
// Examples:
// countVowels("Hello") == 2
// countVowels("") == 0
// countVowels("aeiou") == 5
// countVowels("AEIOU") == 5
func countVowels(string: String) -> Int {
let vowels = "aeiouAEIOU"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as an argument and returns the
// number of words in the string.
// Examples:
// countWords("Hello") == 1
// countWords("") == 0
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as an argument and returns the
// number of uppercase letters in the string.
// Examples:
// countUppercase("Hello") == 1
// countUppercase("") == 0
// countUppercase("Hello world") == 2
// countUppercase("Hello world!") == 2
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as an argument and returns the
// number of lowercase letters in the string.
// Examples:
// countLowercase("Hello") == 1
// countLowercase("") == 0
// countLowercase("Hello world") == 5
// countLowercase("Hello world!") == 5
func countLowercase(string: String) -> Int {
var count = 0
for char in string {
if char.isLower {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as an argument and returns the
// number of digits in the string.
// Examples:
// countDigits("Hello") == 0
// countDigits("") == 0
// countDigits("12345") == 5
// countDigits("abcdefg") == 0
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit {
count += 1
}
}
return count
}
// ---------
if char.isUpper { // value of type 'Character' has no member 'isUpper'
if char.isLower { // value of type 'Character' has no member 'isLower'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2..<n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// 12. Write a function which takes a string and returns the number of vowels
// in the string.
// Examples:
// vowels("apple") == 2
// vowels("banana") == 3
// vowels("kiwi") == 0
// vowels("mango") == 3
// vowels("orange") == 4
// vowels("strawberry") == 5
// vowels("watermelon") == 6
// vowels("") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(" ") == 0
// vowels(
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n % 2 == 0 {
return y
} else {
return x
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n % 2 == 0 {
return y
} else {
return x
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
for i in 2...n {
if n % i == 0 {
return y
}
}
return x
}
// -----------------------------------------------------------------------------
// 2. Write a function which takes a string and returns the number of vowels
// in the string.
// Examples:
// vowels("apple") == 2
// vowels("banana") == 3
// vowels("grapefruit") == 5
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi") == 2
// vowels("kiwi
// XCTAssertTrue failed
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter(isOdd).map(square).reduce(0, +)
}
func lowercase(str: String) -> String {
return str.lowercase
}
func uppercase(str: String) -> String {
return str.uppercase
}
func titlecase(str: String) -> String {
return str.capitalized
}
func capitalize(str: String) -> String {
return str.capitalized
}
func sentenceCase(str: String) -> String {
return str.capitalized
}
func sentenceSentenceCase(str: String) -> String {
return str.capitalized
}
func sentenceSentenceSentenceCase(str: String) -> String {
return str.capitalized
}
func sentenceSentenceSentenceSentenceCase(str: String) -> String {
return str.capitalized
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter(isOdd).map(square).reduce(0, +)
}
// 1.1.2
// Given a string, return the string with all the letters converted to lowercase.
// If the input string is empty, return an empty string.
// lowercase("Hello") == "hello"
// lowercase("") == ""
// lowercase("123") == "123"
func lowercase(str: String) -> String {
return str.lowercase
}
// 1.1.3
// Given a string, return the string with all the letters converted to uppercase.
// If the input string is empty, return an empty string.
// uppercase("Hello") == "HELLO"
// uppercase("") == ""
// uppercase("123") == "123"
func uppercase(str: String) -> String {
return str.uppercase
}
// 1.1.4
// Given a string, return the string with all the letters converted to titlecase.
// If the input string is empty, return an empty string.
// titlecase("Hello") == "Hello"
// titlecase("") == ""
// titlecase("123") == "123"
func titlecase(str: String) -> String {
return str.capitalized
}
// 1.1.5
// Given a string, return the string with all the letters converted to lowercase,
// then capitalize the first letter of each word.
// If the input string is empty, return an empty string.
// capitalize("Hello") == "Hello"
// capitalize("") == ""
// capitalize("123") == "123"
func capitalize(str: String) -> String {
return str.capitalized
}
// 1.1.6
// Given a string, return the string with all the letters converted to lowercase,
// then capitalize the first letter of each sentence.
// If the input string is empty, return an empty string.
// sentenceCase("Hello") == "Hello"
// sentenceCase("") == ""
// sentenceCase("123") == "123"
func sentenceCase(str: String) -> String {
return str.capitalized
}
// 1.1.7
// Given a string, return the string with all the letters converted to lowercase,
// then capitalize the first letter of each sentence, then capitalize the first
// letter of each sentence.
// If the input string is empty, return an empty string.
// sentenceSentenceCase("Hello") == "Hello"
// sentenceSentenceCase("") == ""
// sentenceSentenceCase("123") == "123"
func sentenceSentenceCase(str: String) -> String {
return str.capitalized
}
// 1.1.8
// Given a string, return the string with all the letters converted to lowercase,
// then capitalize the first letter of each sentence, then capitalize the first
// letter of each sentence, then capitalize the first letter of each sentence.
// If the input string is empty, return an empty string.
// sentenceSentenceSentenceCase("Hello") == "Hello"
// sentenceSentenceSentenceCase("") == ""
// sentenceSentenceSentenceCase("123") == "123"
func sentenceSentenceSentenceCase(str: String) -> String {
return str.capitalized
}
// 1.1.9
// Given a string, return the string with all the letters converted to lowercase,
// then capitalize the first letter of each sentence, then capitalize the first
// letter of each sentence, then capitalize the first letter of each sentence,
// then capitalize the first letter of each sentence.
// If the input string is empty, return an empty string.
// sentenceSentenceSentenceSentenceCase("Hello") == "Hello"
// sentenceSentenceSentenceSentenceCase("") == ""
// sentenceSentenceSentenceSentenceCase("123") == "123"
func sentenceSentenceSentenceSentenceCase(str: String) -> String {
return str.capitalized
}
// 1.1.10
return lst.filter(isOdd).map(square).reduce(0, +) // cannot find 'square' in scope
return lst.filter(isOdd).map(square).reduce(0, +) // converting non-escaping value to '(Double) throws -> Int' may allow it to escape
return lst.filter(isOdd).map(square).reduce(0, +) // cannot find 'isOdd' in scope
return str.lowercase // value of type 'String' has no member 'lowercase'
return str.uppercase // value of type 'String' has no member 'uppercase'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
if num % 2 == 1 && num >= 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------
if num % 2 == 1 && num >= 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && Int(num) == num {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && Int(num) == num {
sum += num * num
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------
if num > 0 && Int(num) == num { // cannot convert value of type 'Double' to expected argument type 'Int'
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 && i > 0 {
sum += i * i
}
}
return sum
}
func doubleTheDifference(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 0 && i > 0 {
sum += i
}
}
return sum
}
func doubleTheDifference(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 && i > 0 {
sum += i
}
}
return sum
}
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 0 && i > 0 {
sum += i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 && i > 0 {
sum += i * i
}
}
return sum
}
// 2. Given an array of numbers, return the sum of the numbers in the array that are even.
// Ignore numbers that are negative or not integers. If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 2
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 8
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 0 && i > 0 {
sum += i
}
}
return sum
}
// 3. Given an array of numbers, return the sum of the numbers in the array that are odd.
// Ignore numbers that are negative or not integers. If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 8
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 && i > 0 {
sum += i
}
}
return sum
}
// 4. Given an array of numbers, return the sum of the numbers in the array that are even.
// Ignore numbers that are negative or not integers. If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 2
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 8
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 0 && i > 0 {
sum += i
}
}
return sum
}
// 5. Given an array of numbers, return the sum of the numbers in the array that are odd.
// Ignore numbers that are negative or not integers. If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 8
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Int]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 && i > 0 {
sum += i
}
}
return sum
}
// 6. Given an array of numbers, return the sum of the numbers in the array that are even.
// Ignore numbers that are negative or not integers. If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 2
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 8
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 0 && i > 0 {
sum += i
}
}
return sum
}
// 7. Given an array of numbers, return the sum of the numbers in the array
if i % 2 != 0 && i > 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Int]) -> Int { // invalid redeclaration of 'doubleTheDifference(lst:)'
func doubleTheDifference(lst: [Double]) -> Int { // invalid redeclaration of 'doubleTheDifference(lst:)'
if i % 2 == 0 && i > 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num >= 0 {
sum += num * num
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
if num % 2 == 1 && num >= 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 && i >= 0 {
sum += i * i
}
}
return sum
}
func firstLast(str: String) -> String {
if str.length() < 2 {
return str
} else {
return str.substring(1) + str[0]
}
}
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 && i >= 0 {
sum += i * i
}
}
return sum
}
// 2. Write a function that takes a string and returns a string with the first
// and last characters swapped. If the string is less than two characters long,
// return the string unchanged.
// firstLast("Hello") == "oHell"
// firstLast("a") == "a"
// firstLast("") == ""
func firstLast(str: String) -> String {
if str.length() < 2 {
return str
} else {
return str.substring(1) + str[0]
}
}
// 3. Write a function that takes a string and returns a string with all the
// vowels removed.
// noVowels("Hey") == "Hy"
// noVowels("Happy Birthday") == "Hppy Brthdy"
// noVowels("") == ""
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
// 4. Write a function that takes a string and returns a string with all the
// vowels removed.
// noVowels("Hey") == "Hy"
// noVowels("Happy Birthday") == "Hppy Brthdy"
// noVowels("") == ""
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
// 5. Write a function that takes a string and returns a string with all the
// vowels removed.
// noVowels("Hey") == "Hy"
// noVowels("Happy Birthday") == "Hppy Brthdy"
// noVowels("") == ""
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
// 6. Write a function that takes a string and returns a string with all the
// vowels removed.
// noVowels("Hey") == "Hy"
// noVowels("Happy Birthday") == "Hppy Brthdy"
// noVowels("") == ""
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
// 7. Write a function that takes a string and returns a string with all the
// vowels removed.
// noVowels("Hey") == "Hy"
// noVowels("Happy Birthday") == "Hppy Brthdy"
// noVowels("") == ""
func noVowels(str: String) -> String {
var newStr = ""
for i in str {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
newStr += i
}
}
return newStr
}
// 8. Write a function that takes a string and
if i % 2 == 1 && i >= 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
if str.length() < 2 { // value of type 'String' has no member 'length'
return str.substring(1) + str[0] // no exact matches in call to instance method 'substring'
return str.substring(1) + str[0] // cannot convert value of type 'Int' to expected argument type 'Range<String.Index>'
newStr += i // cannot convert value of type 'Character' to expected argument type 'String'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num > 0 {
sum += num * num
}
}
return sum
}
func stringChars(s: String) -> String {
if s.isEmpty {
return ""
}
var result = ""
if s.count > 1 {
result += s[1..<s.count - 1]
}
result += s[1] * 2
return result
}
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 && num > 0 {
sum += num * num
}
}
return sum
}
// 14. Given a string, return a new string with the first and last chars removed
// and double the second char.
// stringChars("Hello") == "elloo"
// stringChars("a") == "aa"
// stringChars("") == ""
func stringChars(s: String) -> String {
if s.isEmpty {
return ""
}
var result = ""
if s.count > 1 {
result += s[1..<s.count - 1]
}
result += s[1] * 2
return result
}
// 15. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
// 16. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
// 17. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
// 18. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
// 19. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
for char in s {
if char.isDigit {
sum += Int(char)!
}
}
return sum
}
// 20. Given a string, return the sum of the numbers in the string.
// Ignore any non-numeric characters.
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum =
if num % 2 == 1 && num > 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
result += s[1..<s.count - 1] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
result += s[1] * 2 // operator function '+=' requires that 'RunLoop.SchedulerTimeType.Stride' conform to 'Sequence'
result += s[1] * 2 // binary operator '*' cannot be applied to operands of type 'Character' and 'RunLoop.SchedulerTimeType.Stride'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
sum += Int(char)! // cannot convert value of type 'Character' to expected argument type 'String'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 && i >= 0 {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 && i >= 0 {
sum += i * i
}
}
return sum
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
if i % 2 == 1 && i >= 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter { $0 > 0 && Int($0) == $0 }.map { $0 * $0 }.reduce(0, \+)
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
return lst.filter { $0 > 0 && Int($0) == $0 }.map { $0 * $0 }.reduce(0, \+)
}
// 10. Write a function that takes a string and returns the number of vowels in the string.
// The vowel letters are a, e, i, o, u.
// countVowels("abcdefghijklmnopqrstuvwxyz") == 5
// countVowels("") == 0
// countVowels("bcdfghjklmnpqrstvwxyz") == 0
// countVowels("aeiou") == 5
// countVowels("aeiouaeiou") == 10
// countVowels("AEIOUaeiou") == 5
// countVowels("AEIOUaeiouAEIOU") == 10
// countVowels("aeiouAEIOU") == 5
// countVowels("aeiouaeiouaeiouaeiouaeiou") == 20
// countVowels("aeiouAEIOUaeiouAEIOUaeiouAEIOU") == 20
// countVowels("aeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOU") == 40
// countVowels("aeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiouAEIOUaeiou
return lst.filter { $0 > 0 && Int($0) == $0 }.map { $0 * $0 }.reduce(0, \+) // cannot convert value of type 'Double' to expected argument type 'Int'
return lst.filter { $0 > 0 && Int($0) == $0 }.map { $0 * $0 }.reduce(0, \+) // expected expression path in Swift key path
return lst.filter { $0 > 0 && Int($0) == $0 }.map { $0 * $0 }.reduce(0, \+) // missing argument for parameter #2 in call
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.map { (score, guess) -> Int in
if score == guess {
return 0
} else {
return abs(score - guess)
}
}
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
return game.map { (score, guess) -> Int in
if score == guess {
return 0
} else {
return abs(score - guess)
}
}
}
// solution 2
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return game.map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 3
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess).map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 4
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 5
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 6
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 7
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 8
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 9
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 10
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 11
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 12
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 13
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 14
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 15
// func compare(game: [Int], guess: [Int]) -> [Int] {
// return zip(game, guess)
// .map { (score, guess) -> Int in
// return abs(score - guess)
// }
// }
// solution 16
// func compare(game: [Int], guess: [Int]) -> [Int] {
return game.map { (score, guess) -> Int in // contextual closure type '(Int) throws -> Int' expects 1 argument, but 2 were used in closure body
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
func differenceMaxMin(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
return max - min
}
func checkPositive(arr: [Int]) -> Bool {
for i in 0..<arr.count {
if arr[i] == 0 {
for j in i..<arr.count {
if arr[j] == 1 {
return true
}
}
}
}
return false
}
func smallBigDiff(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
return max - min
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
// 2.
// Given an array of integers, return the sum of all the positive integers in the array.
// example:
// sumOfPositives([1, 2, 3, -4, 5]) == 10
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
// 3.
// Given an array of integers, return the difference between the largest and smallest integers in the array.
// example:
// differenceMaxMin([10, 4, 1, 4, -10, -50, 32, 21]) == 82
func differenceMaxMin(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
return max - min
}
// 4.
// Given an array of integers, return true if the array contains a 0 with a 1 somewhere later in the array.
// example:
// checkPositive([1, 2, 3, 4, 5]) == true
// checkPositive([1, 2, 3, 4, 0]) == true
// checkPositive([-1, 1, 2, 3, 4, 5]) == false
func checkPositive(arr: [Int]) -> Bool {
for i in 0..<arr.count {
if arr[i] == 0 {
for j in i..<arr.count {
if arr[j] == 1 {
return true
}
}
}
}
return false
}
// 5.
// Given an array of integers, return the difference between the largest and smallest integers in the array.
// example:
// smallBigDiff([10, 4, 1, 4, -10, -50, 32, 21]) == 32
func smallBigDiff(arr: [Int]) -> Int {
var min = arr[0]
var max = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
return max - min
}
// 6.
// Given an array of integers, return the sum of all the positive integers in the array.
// example:
// sumOfPositives([1, 2, 3, -4, 5]) == 10
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
// 7.
// Given an array of integers, return the sum of all the positive integers in the array.
// example:
// sumOfPositives([1, 2, 3, -4, 5]) == 10
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
if arr[i] > 0 {
sum += arr[i]
}
}
return sum
}
// 8.
// Given an array of integers, return the sum of all the positive integers in the array.
// example:
// sumOfPositives([1, 2, 3, -4, 5]) == 10
func sumOfPositives(arr: [Int]) -> Int {
var sum = 0
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
return result.reversed
}
func sumNumbers(input: String) -> Int {
var result = 0
var currentNumber = ""
for char in input {
if char.isDigit {
currentNumber += char
} else {
if currentNumber.count > 0 {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber.count > 0 {
result += Int(currentNumber)
}
return result
}
func reverseInner(input: String) -> String {
var result = ""
var current = ""
for char in input {
if char == " " {
if current.count > 1 {
result += current.reversed
}
current = ""
} else {
current += char
}
}
if current.count > 1 {
result += current.reversed
}
return result
}
func isPalindrome(input: String) -> Bool {
var result = true
for i in 0..<input.count / 2 {
if input[i] != input[input.count - i - 1] {
result = false
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
// 2.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// example:
// "Example Input" ==> "iNPUT eXAMPLE"
// "Example Input" ==> "iNPUT eXAMPLE"
// "Example Input" ==> "iNPUT eXAMPLE"
func changeCase(input: String) -> String {
var result = ""
for char in input {
if char.isUpper {
result += char.lower
} else {
result += char.upper
}
}
return result.reversed
}
// 3.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9').
// example:
// "abc123xyz" ==> 123
// "aa11b33" ==> 44
// "7 11" ==> 18
func sumNumbers(input: String) -> Int {
var result = 0
var currentNumber = ""
for char in input {
if char.isDigit {
currentNumber += char
} else {
if currentNumber.count > 0 {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber.count > 0 {
result += Int(currentNumber)
}
return result
}
// 4.
// Given a string, return a new string with the inner characters (besides the first and last)
// reversed.
// example:
// "abcedf" ==> "aecdbf"
// "abc" ==> "cba"
// "a" ==> "a"
func reverseInner(input: String) -> String {
var result = ""
var current = ""
for char in input {
if char == " " {
if current.count > 1 {
result += current.reversed
}
current = ""
} else {
current += char
}
}
if current.count > 1 {
result += current.reversed
}
return result
}
// 5.
// Given a string, return the boolean True if it is a palindrome, and False if not.
// A palindrome is any string that reads the same forwards and backwards.
// example:
// "topot" ==> True
// "cat" ==> False
// "racecar" ==> True
// "anna" ==> True
// "code" ==> False
func isPalindrome(input: String) -> Bool {
var result = true
for i in 0..<input.count / 2 {
if input[i] != input[input.count - i - 1] {
result = false
}
}
return result
}
// 6.
// Given a string, return a new string with the inner characters (besides the first and last)
// reversed.
// example:
// "abcedf" ==> "aecdbf"
// "abc" ==> "cba"
// "a" ==> "a"
func reverseInner(input: String) -> String {
var result = ""
var current = ""
for char in input {
if char == " " {
if current.count > 1 {
result += current.reversed
}
current = ""
} else
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lower // value of type 'Character' has no member 'lower'
result += char.upper // value of type 'Character' has no member 'upper'
return result.reversed // no 'reversed' candidates produce the expected contextual result type 'String'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
currentNumber += char // cannot convert value of type 'Character' to expected argument type 'String'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += current.reversed // binary operator '+=' cannot be applied to operands of type 'String' and '() -> [String.Element]' (aka '() -> Array<Character>')
current += char // cannot convert value of type 'Character' to expected argument type 'String'
result += current.reversed // binary operator '+=' cannot be applied to operands of type 'String' and '() -> [String.Element]' (aka '() -> Array<Character>')
if input[i] != input[input.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if input[i] != input[input.count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
if game[i] == guess[i] {
result.append(0)
} else {
result.append(abs(game[i] - guess[i]))
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
result = ""
}
if count == max {
result += extension + "."
}
}
return result.substring(0, result.count - 1)
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
result = ""
}
if count == max {
result += extension + "."
}
}
return result.substring(0, result.count - 1)
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
result += extension + "." // expected type name in extension declaration
result += extension + "." // declaration is only valid at file scope
result += extension + "." // expected '{' in extension
result += extension + "." // expected expression after operator
return result.substring(0, result.count - 1) // no exact matches in call to instance method 'substring'
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for letter in extension {
if letter == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
result = "\(className).\(maxExtension)"
return result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for letter in extension {
if letter == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
result = "\(className).\(maxExtension)"
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------
for extension in extensions { // expected Sequence expression for for-each loop
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for letter in extension { // expected Sequence expression for for-each loop
for letter in extension { // expected '{' to start the body of for-each loop
maxExtension = extension // expected '{' in extension
maxExtension = extension // declaration is only valid at file scope
maxExtension = extension // expected expression in assignment
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count })
let strongestExtension = sortedExtensions.first!
return "\(className).\(strongestExtension)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count })
let strongestExtension = sortedExtensions.first!
return "\(className).\(strongestExtension)"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count }) // cannot find operator '<=>' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
maxExtension = extension // expected '{' in extension
maxExtension = extension // declaration is only valid at file scope
maxExtension = extension // expected expression in assignment
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
maxExtension = extension // expected '{' in extension
maxExtension = extension // declaration is only valid at file scope
maxExtension = extension // expected expression in assignment
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
maxExtension = extension // expected '{' in extension
maxExtension = extension // declaration is only valid at file scope
maxExtension = extension // expected expression in assignment
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { (extension1: String, extension2: String) -> Bool in
let cap1 = extension1.count(for: .uppercase)
let cap2 = extension2.count(for: .uppercase)
let sm1 = extension1.count(for: .lowercase)
let sm2 = extension2.count(for: .lowercase)
return cap1 - sm1 > cap2 - sm2
})
return "\(className).\(sortedExtensions[0])"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { (extension1: String, extension2: String) -> Bool in
let cap1 = extension1.count(for: .uppercase)
let cap2 = extension2.count(for: .uppercase)
let sm1 = extension1.count(for: .lowercase)
let sm2 = extension2.count(for: .lowercase)
return cap1 - sm1 > cap2 - sm2
})
return "\(className).\(sortedExtensions[0])"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
let cap1 = extension1.count(for: .uppercase) // cannot call value of non-function type 'Int'
let cap1 = extension1.count(for: .uppercase) // cannot infer contextual base in reference to member 'uppercase'
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count })
return "\(className).\(sortedExtensions.first!)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count })
return "\(className).\(sortedExtensions.first!)"
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
let sortedExtensions = extensions.sorted(by: { $0.count <=> $1.count }) // cannot find operator '<=>' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
func ReverseString(s: String) -> String {
return String(s.reversed())
}
func TwoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
func HasCycle(head: ListNode?) -> Bool {
var slow = head
var fast = head
while fast != nil && fast!.next != nil {
slow = slow!.next
fast = fast!.next!.next
if slow == fast {
return true
}
}
return false
}
func DetectCycle(head: ListNode?) -> ListNode? {
var slow = head
var fast = head
while fast != nil && fast!.next != nil {
slow = slow!.next
fast = fast!.next!.next
if slow == fast {
var ptr = head
while ptr != slow {
ptr = ptr!.next
slow = slow!.next
}
return ptr
}
}
return nil
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var max = 0
var maxExtension = ""
for extension in extensions {
var count = 0
for char in extension {
if char == Character(UppercaseLetter) {
count += 1
}
}
if count > max {
max = count
maxExtension = extension
}
}
return "\(className).\(maxExtension)"
}
// 10. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
func ReverseString(s: String) -> String {
return String(s.reversed())
}
// 11. Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
func TwoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if nums[i] + nums[j] == target {
result.append(i)
result.append(j)
return result
}
}
}
return result
}
// 12. Given a linked list, determine if it has a cycle in it.
// Follow up:
// Can you solve it without using extra space?
// Example:
// Input: head = [3,2,0,-4], pos = 1
// Output: true
// Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
func HasCycle(head: ListNode?) -> Bool {
var slow = head
var fast = head
while fast != nil && fast!.next != nil {
slow = slow!.next
fast = fast!.next!.next
if slow == fast {
return true
}
}
return false
}
// 13. Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
// To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
// Note: Do not modify the linked list.
// Example 1:
// Input: head = [3,2,0,-4], pos = 1
// Output: tail connects to node index 1
// Explanation: There is a cycle in the linked list, where tail connects to the second node.
func DetectCycle(head: ListNode?) -> ListNode? {
var slow = head
var fast = head
while fast != nil && fast!.next != nil {
slow = slow!.next
fast = fast!.next!.next
if slow == fast {
var ptr = head
while ptr != slow {
ptr = ptr!.next
slow = slow!.next
}
return ptr
}
}
return nil
}
// 14. Given a linked list, determine if it has a cycle in it.
// To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
// Example 1:
// Input: head = [3,2,0,-4], pos = 1
// Output: true
// Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
func HasCycle(head: ListNode?) -> Bool {
var slow = head
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
for char in extension { // expected Sequence expression for for-each loop
for char in extension { // expected '{' to start the body of for-each loop
maxExtension = extension // expected '{' in extension
maxExtension = extension // declaration is only valid at file scope
maxExtension = extension // expected expression in assignment
} // expected type name in extension declaration
func HasCycle(head: ListNode?) -> Bool { // cannot find type 'ListNode' in scope
func DetectCycle(head: ListNode?) -> ListNode? { // cannot find type 'ListNode' in scope
func DetectCycle(head: ListNode?) -> ListNode? { // cannot find type 'ListNode' in scope
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { (extension1: String, extension2: String) -> Bool in
let extension1Capitalized = extension1.uppercased()
let extension2Capitalized = extension2.uppercased()
let extension1Lowercased = extension1.lowercased()
let extension2Lowercased = extension2.lowercased()
let extension1CapitalizedStrength = extension1Capitalized.count - extension1Lowercased.count
let extension2CapitalizedStrength = extension2Capitalized.count - extension2Lowercased.count
return extension1CapitalizedStrength > extension2CapitalizedStrength ||
extension1CapitalizedStrength == extension2CapitalizedStrength && extension1.compare(extension2) == .orderedAscending
})
return "\(className).\(sortedExtensions.first!)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let sortedExtensions = extensions.sorted(by: { (extension1: String, extension2: String) -> Bool in
let extension1Capitalized = extension1.uppercased()
let extension2Capitalized = extension2.uppercased()
let extension1Lowercased = extension1.lowercased()
let extension2Lowercased = extension2.lowercased()
let extension1CapitalizedStrength = extension1Capitalized.count - extension1Lowercased.count
let extension2CapitalizedStrength = extension2Capitalized.count - extension2Lowercased.count
return extension1CapitalizedStrength > extension2CapitalizedStrength ||
extension1CapitalizedStrength == extension2CapitalizedStrength && extension1.compare(extension2) == .orderedAscending
})
return "\(className).\(sortedExtensions.first!)"
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var aArray = Array(a)
var bArray = Array(b)
var aLength = a.length
var bLength = b.length
var aSubString = ""
var bSubString = ""
var aSubStringArray = []
var bSubStringArray = []
var bSubStringArrayLength = 0
var aSubStringArrayLength = 0
var aSubStringArrayIndex = 0
var bSubStringArrayIndex = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
var bSubStringArrayIndexLength = 0
var aSubStringArrayIndexLength = 0
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var aArray = Array(a)
var bArray = Array(b)
var aLength = aArray.count
var bLength = bArray.count
var aIndex = 0
var bIndex = 0
while (aIndex < aLength) {
if (aArray[aIndex] == bArray[bIndex]) {
bIndex += 1
if (bIndex == bLength) {
result = true
break
}
} else {
bIndex = 0
}
aIndex += 1
}
return result
}
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var aArray = Array(a)
var bArray = Array(b)
var aLength = aArray.count
var bLength = bArray.count
var aIndex = 0
var bIndex = 0
while (aIndex < aLength) {
if (aArray[aIndex] == bArray[bIndex]) {
bIndex += 1
if (bIndex == bLength) {
result = true
break
}
} else {
bIndex = 0
}
aIndex += 1
}
return result
}
// 10. Write a function that returns the string "something" if the input string is "something" or "nothing".
// If the input string is "something else", return the input string.
// cycStringCheck("something") == "something"
// cycStringCheck("nothing") == "nothing"
// cycStringCheck("something else") == "something else"
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
}
return result
}
// 11. Write a function that returns the string "something" if the input string is "something" or "nothing".
// If the input string is "something else", return the input string.
// cycStringCheck("something") == "something"
// cycStringCheck("nothing") == "nothing"
// cycStringCheck("something else") == "something else"
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
}
return result
}
// 12. Write a function that returns the string "something" if the input string is "something" or "nothing".
// If the input string is "something else", return the input string.
// cycStringCheck("something") == "something"
// cycStringCheck("nothing") == "nothing"
// cycStringCheck("something else") == "something else"
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
}
return result
}
// 13. Write a function that returns the string "something" if the input string is "something" or "nothing".
// If the input string is "something else", return the input string.
// cycStringCheck("something") == "something"
// cycStringCheck("nothing") == "nothing"
// cycStringCheck("something else") == "something else"
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
}
return result
}
// 14. Write a function that returns the string "something" if the input string is "something" or "nothing".
// If the input string is "something else", return the input string.
// cycStringCheck("something") == "something"
// cycStringCheck("nothing") == "nothing"
// cycStringCheck("something else") == "something else"
func cycStringCheck(a: String) -> String {
var result = ""
if (a == "something") {
result = "something"
} else if (a == "nothing") {
result = "nothing"
} else {
result = a
var aArray = Array(a) // variable 'aArray' was never mutated; consider changing to 'let' constant
var bArray = Array(b) // variable 'bArray' was never mutated; consider changing to 'let' constant
var aLength = aArray.count // variable 'aLength' was never mutated; consider changing to 'let' constant
var bLength = bArray.count // variable 'bLength' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
for i in 0..<b.count {
bArray.append(b[i])
}
for i in 0..<b.count {
bArray.remove(at: 0)
bArray.append(b[i])
if a.contains(String(bArray)) {
result = true
}
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
for i in 0..<b.count {
bArray.append(b[i])
}
for i in 0..<b.count {
bArray.remove(at: 0)
bArray.append(b[i])
if a.contains(String(bArray)) {
result = true
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
//
bArray.append(b[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
bArray.append(b[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var aArray = Array(a)
var bArray = Array(b)
var aLength = a.length
var bLength = b.length
var aIndex = 0
var bIndex = 0
while (aIndex < aLength) {
if (aArray[aIndex] == bArray[bIndex]) {
bIndex += 1
if (bIndex == bLength) {
result = true
break
}
} else {
bIndex = 0
}
aIndex += 1
}
return result
}
func firstNonRepeatingCharacter(s: String) -> Int {
var result = -1
var sArray = Array(s)
var sLength = s.length
var sIndex = 0
var sChar = ""
var sCount = 0
while (sIndex < sLength) {
sChar = sArray[sIndex]
sCount = 0
var i = 0
while (i < sLength) {
if (sArray[i] == sChar) {
sCount += 1
}
i += 1
}
if (sCount == 1) {
result = sIndex
break
}
sIndex += 1
}
return result
}
func lastOccurrence(s: String, c: String) -> Int {
var result = -1
var sArray = Array(s)
var sLength = s.length
var sIndex = 0
var sChar = ""
while (sIndex < sLength) {
sChar = sArray[sIndex]
if (sChar == c) {
result = sIndex
}
sIndex += 1
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var aArray = Array(a)
var bArray = Array(b)
var aLength = a.length
var bLength = b.length
var aIndex = 0
var bIndex = 0
while (aIndex < aLength) {
if (aArray[aIndex] == bArray[bIndex]) {
bIndex += 1
if (bIndex == bLength) {
result = true
break
}
} else {
bIndex = 0
}
aIndex += 1
}
return result
}
// 14. Write a function that returns the index of the first non-repeating character in a string.
// If there isn't one, return -1.
// firstNonRepeatingCharacter("abcd") == 0
// firstNonRepeatingCharacter("abab") == -1
// firstNonRepeatingCharacter("axxxb") == 3
func firstNonRepeatingCharacter(s: String) -> Int {
var result = -1
var sArray = Array(s)
var sLength = s.length
var sIndex = 0
var sChar = ""
var sCount = 0
while (sIndex < sLength) {
sChar = sArray[sIndex]
sCount = 0
var i = 0
while (i < sLength) {
if (sArray[i] == sChar) {
sCount += 1
}
i += 1
}
if (sCount == 1) {
result = sIndex
break
}
sIndex += 1
}
return result
}
// 15. Write a function that returns the index of the first occurrence of non-repeating
// character in a string. If there isn't one, return -1.
// firstNonRepeatingCharacter("abcd") == 0
// firstNonRepeatingCharacter("abab") == -1
// firstNonRepeatingCharacter("axxxb") == 3
func firstNonRepeatingCharacter(s: String) -> Int {
var result = -1
var sArray = Array(s)
var sLength = s.length
var sIndex = 0
var sChar = ""
var sCount = 0
while (sIndex < sLength) {
sChar = sArray[sIndex]
sCount = 0
var i = 0
while (i < sLength) {
if (sArray[i] == sChar) {
sCount += 1
}
i += 1
}
if (sCount == 1) {
result = sIndex
break
}
sIndex += 1
}
return result
}
// 16. Write a function that returns the index of the last occurrence of a character in a string.
// If it does not occur, it should return -1.
// lastOccurrence("abcd", "b") == 1
// lastOccurrence("abcd", "c") == 2
// lastOccurrence("abcd", "e") == -1
func lastOccurrence(s: String, c: String) -> Int {
var result = -1
var sArray = Array(s)
var sLength = s.length
var sIndex = 0
var sChar = ""
while (sIndex < sLength) {
sChar = sArray[sIndex]
if (sChar == c) {
result = sIndex
}
sIndex += 1
}
return result
}
// 17. Write a function that returns the index of the last occurrence of a character in a string.
// If it does not occur, it should return -1.
// lastOccurrence("abcd", "b") == 1
// lastOccurrence("abcd", "c") == 2
// lastOccurrence("abcd", "e") == -1
func lastOccurrence(s: String, c: String) -> Int {
var aLength = a.length // value of type 'String' has no member 'length'
var bLength = b.length // value of type 'String' has no member 'length'
var sLength = s.length // value of type 'String' has no member 'length'
sChar = sArray[sIndex] // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
if (sArray[i] == sChar) { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
var sLength = s.length // value of type 'String' has no member 'length'
sChar = sArray[sIndex] // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
var aArray = Array(a)
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
bArray.remove(at: j)
break
}
}
if bArray.count == 0 {
result = true
break
}
bArray = Array(b)
}
return result
}
func count7(number: Int) -> Int {
var result = 0
var numberArray = Array(number)
for i in numberArray {
if i == 7 {
result += 1
}
}
return result
}
func stringX(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if i == "x" {
result += "y"
} else {
result += i
}
}
return result
}
func allStar(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if result.count == 0 {
result += i
} else {
result += "*" + i
}
}
return result
}
func endX(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if i == "x" {
result += "x"
} else {
result += i
}
}
return result
}
func pairStar(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if result.count == 0 {
result += i
} else {
result += "*" + i
}
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
var aArray = Array(a)
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
bArray.remove(at: j)
break
}
}
if bArray.count == 0 {
result = true
break
}
bArray = Array(b)
}
return result
}
// 2. Write a function that returns the number of times the number 7 occurs in the given integer.
// count7(717) == 2
// count7(7) == 1
// count7(12371237) == 1
func count7(number: Int) -> Int {
var result = 0
var numberArray = Array(number)
for i in numberArray {
if i == 7 {
result += 1
}
}
return result
}
// 3. Given a string, compute recursively a new string where all the lowercase 'x' chars have been changed to 'y' chars.
// stringX("xaxb") == "yaaxb"
// stringX("abc") == "abc"
// stringX("xx") == "yy"
func stringX(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if i == "x" {
result += "y"
} else {
result += i
}
}
return result
}
// 4. Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".
// allStar("hello") == "h*e*l*l*o"
// allStar("x") == "x"
// allStar("1234") == "1*2*3*4"
func allStar(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if result.count == 0 {
result += i
} else {
result += "*" + i
}
}
return result
}
// 5. Given a string, compute recursively a new string where all the lowercase 'x' chars have been moved to the end of the string.
// endX("xxre") == "rexx"
// endX("xxhixx") == "hixxxx"
// endX("xhixhix") == "hihixxx"
// endX("hi") == "hi"
// endX("x") == "x"
// endX("") == ""
func endX(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if i == "x" {
result += "x"
} else {
result += i
}
}
return result
}
// 6. Given a string, compute recursively a new string where all the adjacent chars are now separated by a "*".
// pairStar("hello") == "hel*lo"
// pairStar("xxyy") == "x*xy*y"
// pairStar("aaaa") == "a*a*a*a"
func pairStar(string: String) -> String {
var result = ""
var stringArray = Array(string)
for i in stringArray {
if result.count == 0 {
result += i
} else {
result += "*" + i
}
}
return result
}
// 7. Given two strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
// stringMatch("xxcaazz", "xxbaaz"
var aArray = Array(a) // initialization of variable 'aArray' was never used; consider replacing with assignment to '_' or removing it
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
var numberArray = Array(number) // missing argument label 'arrayLiteral:' in call
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += "*" + i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
result += "*" + i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
if b.count <= a.count {
for i in 0..<b.count {
if a.contains(b.prefix(b.count - i)) {
result = true
break
}
}
}
return result
}
func countCode(str: String) -> Int {
var result = 0
for i in 0..<str.count {
if str[i..<i+3] == "code" {
result += 1
}
}
return result
}
func repeatSeparator(word: String, sep: String, count: Int) -> String {
var result = ""
for i in 0..<count {
result += word
if i != count - 1 {
result += sep
}
}
return result
}
func doubleX(str: String) -> Bool {
var result = false
for i in 0..<str.count {
if str[i] == "x" {
if i != str.count - 1 {
if str[i+1] == "x" {
result = true
break
}
}
}
}
return result
}
func doubleX(str: String) -> Bool {
var result = false
for i in 0..<str.count {
if str[i] == "x" {
if i != str.count - 1 {
if str[i+1] == "x" {
if i != 0 {
if str[i-1] == "x" {
result = true
break
}
}
}
}
}
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
if b.count <= a.count {
for i in 0..<b.count {
if a.contains(b.prefix(b.count - i)) {
result = true
break
}
}
}
return result
}
// 12. Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(str: String) -> Int {
var result = 0
for i in 0..<str.count {
if str[i..<i+3] == "code" {
result += 1
}
}
return result
}
// 13. Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string.
// repeatSeparator("Word", "X", 3) → "WordXWordXWord"
// repeatSeparator("This", "And", 2) → "ThisAndThis"
// repeatSeparator("This", "And", 1) → "This"
func repeatSeparator(word: String, sep: String, count: Int) -> String {
var result = ""
for i in 0..<count {
result += word
if i != count - 1 {
result += sep
}
}
return result
}
// 14. Given a string, return true if the first instance of "x" in the string is immediately followed by another "x".
// doubleX("axxbb") → true
// doubleX("axaxax") → false
// doubleX("xxxxx") → true
func doubleX(str: String) -> Bool {
var result = false
for i in 0..<str.count {
if str[i] == "x" {
if i != str.count - 1 {
if str[i+1] == "x" {
result = true
break
}
}
}
}
return result
}
// 15. Given a string, return true if the first instance of "x" in the string is immediately followed by another "x" that is 7 characters from the first "x".
// doubleX("axxxxaxx") → true
// doubleX("axxaxaxx") → false
// doubleX("xxxxx") → false
func doubleX(str: String) -> Bool {
var result = false
for i in 0..<str.count {
if str[i] == "x" {
if i != str.count - 1 {
if str[i+1] == "x" {
if i != 0 {
if str[i-1] == "x" {
result = true
break
}
}
}
}
}
}
return result
}
// 16. Given a string, return true if the first instance of "x" in the string is immediately followed by another "x" that is 7 characters from the first "x".
// doubleX("axxxxaxx") → true
// doubleX("axxaxaxx") → false
// doubleX("xxxxx") → false
func doubleX(str: String) -> Bool {
var result = false
for i in 0..<str.count {
if str[i] == "x" {
if i != str.count - 1 {
if str[i+1] == "x" {
if i != 0 {
if str[i-1] == "x" {
result = true
break
}
}
}
if str[i..<i+3] == "code" { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if str[i] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if str[i+1] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func doubleX(str: String) -> Bool { // invalid redeclaration of 'doubleX(str:)'
if str[i] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if str[i+1] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if str[i-1] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var count = 0
var index = 0
var result = false
var aArray = Array(a)
var bArray = Array(b)
var bArray2 = Array(b)
var bArray3 = Array(b)
var bArray4 = Array(b)
var bArray5 = Array(b)
var bArray6 = Array(b)
var bArray7 = Array(b)
var bArray8 = Array(b)
var bArray9 = Array(b)
var bArray10 = Array(b)
var bArray11 = Array(b)
var bArray12 = Array(b)
var bArray13 = Array(b)
var bArray14 = Array(b)
var bArray15 = Array(b)
var bArray16 = Array(b)
var bArray17 = Array(b)
var bArray18 = Array(b)
var bArray19 = Array(b)
var bArray20 = Array(b)
var bArray21 = Array(b)
var bArray22 = Array(b)
var bArray23 = Array(b)
var bArray24 = Array(b)
var bArray25 = Array(b)
var bArray26 = Array(b)
var bArray27 = Array(b)
var bArray28 = Array(b)
var bArray29 = Array(b)
var bArray30 = Array(b)
var bArray31 = Array(b)
var bArray32 = Array(b)
var bArray33 = Array(b)
var bArray34 = Array(b)
var bArray35 = Array(b)
var bArray36 = Array(b)
var bArray37 = Array(b)
var bArray38 = Array(b)
var bArray39 = Array(b)
var bArray40 = Array(b)
var bArray41 = Array(b)
var bArray42 = Array(b)
var bArray43 = Array(b)
var bArray44 = Array(b)
var bArray45 = Array(b)
var bArray46 = Array(b)
var bArray47 = Array(b)
var bArray48 = Array(b)
var bArray49 = Array(b)
var bArray50 = Array(b)
var bArray51 = Array(b)
var bArray52 = Array(b)
var bArray53 = Array(b)
var bArray54 = Array(b)
var bArray55 = Array(b)
var bArray56 = Array(b)
var bArray57 = Array(b)
var bArray58 = Array(b)
var bArray59 = Array(b)
var bArray60 = Array(b)
var bArray61 = Array(b)
var bArray62 = Array(b)
var bArray63 = Array(b)
var bArray64 = Array(b)
var bArray65 = Array(b)
var bArray66 = Array(b)
var bArray67 = Array(b)
var bArray68 = Array(b)
var bArray69 = Array(b)
var bArray70 = Array(b)
var bArray71 = Array(b)
var bArray72 = Array(b)
var bArray73 = Array(b)
var bArray74 = Array(b)
var bArray75 = Array(b)
var bArray76 = Array(b)
var bArray77 = Array(b)
var bArray78 = Array(b)
var bArray79 = Array(b)
var bArray80 = Array(b)
var bArray81 = Array(b)
var bArray82 = Array(b)
var bArray83 = Array(b)
var bArray84 =
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
for i in 0..<a.count {
if a[i..<] == b {
result = true
break
}
}
return result
}
func countCode(s: String) -> Int {
var result = 0
for i in 0..<s.count {
if s[i..<] == "code" {
result += 1
}
}
return result
}
func doubleX(s: String) -> Bool {
var result = false
for i in 0..<s.count {
if s[i] == "x" {
if s[i+1] == "x" {
result = true
break
}
}
}
return result
}
func frontAgain(s: String) -> Bool {
var result = false
if s[0..<2] == s[s.count-2..<] {
result = true
}
return result
}
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
func endOther(a: String, b: String) -> Bool {
var result = false
if a.toLowerCase().last == b.toLowerCase().last {
result = true
}
return result
}
func doubleChar(s: String) -> String {
var result = ""
for i in 0..<s.count {
result += s[i]
result += s[i]
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
for i in 0..<a.count {
if a[i..<] == b {
result = true
break
}
}
return result
}
// 12. Write a function that returns the number of times the string "code" appears anywhere in the given string, except we'll accept any letter for the o's, so "cope" and "cooe" count.
// countCode("aaacodebbb") → 1
// countCode("codexxcode") → 2
// countCode("cozexxcope") → 2
func countCode(s: String) -> Int {
var result = 0
for i in 0..<s.count {
if s[i..<] == "code" {
result += 1
}
}
return result
}
// 13. Given a string, return true if the first instance of "x" in the string is immediately followed by another "x".
// doubleX("axxbb") → true
// doubleX("axaxax") → false
// doubleX("xxxxx") → true
func doubleX(s: String) -> Bool {
var result = false
for i in 0..<s.count {
if s[i] == "x" {
if s[i+1] == "x" {
result = true
break
}
}
}
return result
}
// 14. Given a string, return true if the first 2 chars in the string also appear at the end of the string, such as with "edited".
// frontAgain("edited") → true
// frontAgain("edit") → false
// frontAgain("ed") → true
func frontAgain(s: String) -> Bool {
var result = false
if s[0..<2] == s[s.count-2..<] {
result = true
}
return result
}
// 15. Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
// stringBits("Hello") → "Hlo"
// stringBits("Hi") → "H"
// stringBits("Heeololeo") → "Hello"
func stringBits(s: String) -> String {
var result = ""
for i in 0..<s.count {
if i % 2 == 0 {
result += s[i]
}
}
return result
}
// 16. Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
// endOther("Hiabc", "abc") → true
// endOther("AbC", "HiaBc") → true
// endOther("abc", "abXabc") → true
func endOther(a: String, b: String) -> Bool {
var result = false
if a.toLowerCase().last == b.toLowerCase().last {
result = true
}
return result
}
// 17. Given a string, return a string where for every char in the original, there are two chars.
// doubleChar("The") → "TThhee"
// doubleChar("AAbb") → "AAAAbbbb"
// doubleChar("Hi-There") → "HHii--TThheerree"
func doubleChar(s: String) -> String {
var result = ""
for i in 0..<s.count {
result += s[i]
result += s[i]
}
return result
}
// 18. Return the number of times that the string "hi" appears anywhere in the given string.
// countHi("abc hi ho") → 1
// countHi("ABChi hi") → 2
// countHi("hihi") →
if a[i..<] == b { // '..<' is not a postfix unary operator
if s[i..<] == "code" { // '..<' is not a postfix unary operator
if s[i] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i+1] == "x" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[0..<2] == s[s.count-2..<] { // '..<' is not a postfix unary operator
result += s[i] // no exact matches in call to subscript
if a.toLowerCase().last == b.toLowerCase().last { // value of type 'String' has no member 'toLowerCase'
if a.toLowerCase().last == b.toLowerCase().last { // value of type 'String' has no member 'toLowerCase'
result += s[i] // no exact matches in call to subscript
result += s[i] // no exact matches in call to subscript
func cycpatternCheck(a: String, b: String) -> Bool {
var count = 0
for i in 0..<a.count {
if a[i...] == b {
return true
}
if a[i..<a.count] + a[0..<i] == b {
return true
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var count = 0
for i in 0..<a.count {
if a[i...] == b {
return true
}
if a[i..<a.count] + a[0..<i] == b {
return true
}
}
return false
}
// 2. Write a function that returns the string "something" if the given argument is truthy, and the string "nothing" if the given argument is falsy.
// nothingIfEmpty(null) == "nothing"
// nothingIfEmpty(undefined) == "nothing"
// nothingIfEmpty("") == "nothing"
// nothingIfEmpty(0) == "something"
// nothingIfEmpty(NaN) == "something"
// nothingIfEmpty(false) == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty(true) == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty(1) == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
// nothingIfEmpty("true") == "something"
// nothingIfEmpty("1") == "something"
// nothingIfEmpty("0") == "something"
// nothingIfEmpty("0.1") == "something"
// nothingIfEmpty(" ") == "something"
// nothingIfEmpty("abc") == "something"
// nothingIfEmpty("false") == "something"
var count = 0 // initialization of variable 'count' was never used; consider replacing with assignment to '_' or removing it
if a[i...] == b { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i..<a.count] + a[0..<i] == b { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i..<a.count] + a[0..<i] == b { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
var aArray = Array(a)
var bLength = bArray.count
var aLength = aArray.count
var i = 0
var j = 0
var k = 0
while i < bLength && j < aLength {
if bArray[i] == aArray[j] {
i += 1
j += 1
} else {
j = 0
k += 1
}
}
if i == bLength {
result = true
}
return result
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
var result = false
var bArray = Array(b)
var aArray = Array(a)
var bLength = bArray.count
var aLength = aArray.count
var i = 0
var j = 0
var k = 0
while i < bLength && j < aLength {
if bArray[i] == aArray[j] {
i += 1
j += 1
} else {
j = 0
k += 1
}
}
if i == bLength {
result = true
}
return result
}
// 2. Write a function that returns true if two words have the same length and only one character difference between them.
// The characters must be in the same position (i.e., exactly one character can be substituted for another character).
// isOneEditAway("cat", "dog") == false
// isOneEditAway("cat", "cats") == true
// isOneEditAway("cat", "cut") == true
// isOneEditAway("cat", "cast") == true
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == false
// isOneEditAway("cat", "acta") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat", "at") == true
// isOneEditAway("cat", "act") == true
// isOneEditAway("cat", "actar") == false
// isOneEditAway("cat",
var bArray = Array(b) // variable 'bArray' was never mutated; consider changing to 'let' constant
var aArray = Array(a) // variable 'aArray' was never mutated; consider changing to 'let' constant
var bLength = bArray.count // variable 'bLength' was never mutated; consider changing to 'let' constant
var aLength = aArray.count // variable 'aLength' was never mutated; consider changing to 'let' constant
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs > 0 {
if abs % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func repeatStr(num: Int, str: String) -> String {
return str * num
}
func doubled(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs > 0 {
if abs % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string reversed.
// Example:
// reverseString("hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes an integer and returns a string with the given number of "a"s.
// Example:
// repeatStr(num: 5, str: "Hello") == "HelloHelloHelloHelloHello"
func repeatStr(num: Int, str: String) -> String {
return str * num
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Given an array of integers, return a new array with each value doubled.
// Example:
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// doubled([1, 2, 3]) == [2, 4, 6]
func doubled(nums: [Int]) -> [Int] {
return nums.map { $0 * 2 }
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Given an array of integers, return a new array with each value doubled.
// Example:
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1, nums[1] = 2, nums[2] = 3
// nums[0] = 1,
return str * num // no '*' candidates produce the expected contextual result type 'String'
return str * num // binary operator '*' cannot be applied to operands of type 'String' and 'Int'
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
func reverseString(string: String) -> String {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed
}
func isIsomorphic(s: String, t: String) -> Bool {
var sToT = [Character: Character]()
var tToS = [Character: Character]()
for i in 0..<s.count {
if s[i] != t[i] {
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] {
return false
}
sToT[s[i]] = t[i]
tToS[t[i]] = s[i]
}
}
return true
}
func lengthOfLongestSubstring(string: String) -> Int {
var maxLength = 0
var start = 0
var seen = [Character: Int]()
for i in 0..<string.count {
if seen[string[i]] != nil {
start = max(start, seen[string[i]]! + 1)
}
maxLength = max(maxLength, i - start + 1)
seen[string[i]] = i
}
return maxLength
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var seen = [Int: Int]()
for i in 0..<nums.count {
if seen[target - nums[i]] != nil {
return [seen[target - nums[i]]!, i]
}
seen[nums[i]] = i
}
return []
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
// 2. Write a function that takes a string as input and returns the string reversed.
// Example:
// reverseString("hello") == "olleh"
func reverseString(string: String) -> String {
var reversed = ""
for char in string {
reversed = char + reversed
}
return reversed
}
// 3. Given two strings s and t, determine if they are isomorphic.
// Two strings s and t are isomorphic if the characters in s can be replaced to get t.
// All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
// Example:
// isIsomorphic(s: "egg", t: "add") == true
// isIsomorphic(s: "foo", t: "bar") == false
// isIsomorphic(s: "paper", t: "title") == true
func isIsomorphic(s: String, t: String) -> Bool {
var sToT = [Character: Character]()
var tToS = [Character: Character]()
for i in 0..<s.count {
if s[i] != t[i] {
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] {
return false
}
sToT[s[i]] = t[i]
tToS[t[i]] = s[i]
}
}
return true
}
// 4. Given a string s, find the length of the longest substring without repeating characters.
// Example:
// lengthOfLongestSubstring("abcabcbb") == 3
// lengthOfLongestSubstring("bbbbb") == 1
// lengthOfLongestSubstring("pwwkew") == 3
func lengthOfLongestSubstring(string: String) -> Int {
var maxLength = 0
var start = 0
var seen = [Character: Int]()
for i in 0..<string.count {
if seen[string[i]] != nil {
start = max(start, seen[string[i]]! + 1)
}
maxLength = max(maxLength, i - start + 1)
seen[string[i]] = i
}
return maxLength
}
// 5. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example:
// twoSum(nums: [2,7,11,15], target: 9) == [0,1]
// twoSum(nums: [3,2,4], target: 6) == [1,2]
// twoSum(nums: [3,3], target: 6) == [0,1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var seen = [Int: Int]()
for i in 0..<nums.count {
if seen[target - nums[i]] != nil {
return [seen[target - nums[i]]!, i]
}
seen[nums[i]] = i
}
return []
}
// 6. Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Example:
// twoSum(nums: [2,
reversed = char + reversed // cannot convert value of type 'Character' to expected argument type 'String'
if s[i] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s[i] != t[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if sToT[s[i]] != t[i] || tToS[t[i]] != s[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sToT[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
sToT[s[i]] = t[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
tToS[t[i]] = s[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
tToS[t[i]] = s[i] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if seen[string[i]] != nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
start = max(start, seen[string[i]]! + 1) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
seen[string[i]] = i // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
let digit = abs % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
let digit = abs % 10
if digit % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
even += 1 // left side of mutating operator isn't mutable: 'even' is a 'let' constant
odd += 1 // left side of mutating operator isn't mutable: 'odd' is a 'let' constant
abs /= 10 // left side of mutating operator isn't mutable: 'abs' is a 'let' constant
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// 12. Write a function that takes a string and returns a new string with all vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 13. Write a function that takes a string and returns a new string with all vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 14. Write a function that takes a string and returns a new string with all vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 15. Write a function that takes a string and returns a new string with all vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 16. Write a function that takes a string and returns a new string with all vowels removed.
// Example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if !isVowel(char: char) {
result += char
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// 17. Write a function that takes a string and returns a new string with all vowels removed.
// Example
even += 1 // left side of mutating operator isn't mutable: 'even' is a 'let' constant
odd += 1 // left side of mutating operator isn't mutable: 'odd' is a 'let' constant
abs /= 10 // left side of mutating operator isn't mutable: 'abs' is a 'let' constant
if !isVowel(char: char) { // cannot find 'isVowel' in scope
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs != 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs != 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
func alphabeticalOrder(str: String) -> String {
return String(str.map(Character.init).sorted())
}
func reverseAlphabeticalOrder(str: String) -> String {
return String(str.map(Character.init).sorted().reversed())
}
func alphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted())
}
func reverseAlphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted().reversed())
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let abs = abs(num)
let even = 0
let odd = 0
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// 2. Write a function that takes a string and returns a string with the letters in alphabetical order.
// Example:
// alphabeticalOrder("hello") == "ehllo"
func alphabeticalOrder(str: String) -> String {
return String(str.map(Character.init).sorted())
}
// 3. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// Example:
// reverseAlphabeticalOrder("hello") == "olleh"
func reverseAlphabeticalOrder(str: String) -> String {
return String(str.map(Character.init).sorted().reversed())
}
// 4. Write a function that takes a string and returns a string with the letters in alphabetical order.
// If the string is empty, return an empty string.
// Example:
// alphabeticalOrder("") == ""
func alphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted())
}
// 5. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// If the string is empty, return an empty string.
// Example:
// reverseAlphabeticalOrder("") == ""
func reverseAlphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted().reversed())
}
// 6. Write a function that takes a string and returns a string with the letters in alphabetical order.
// If the string is empty, return an empty string.
// Example:
// alphabeticalOrder("") == ""
func alphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted())
}
// 7. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// If the string is empty, return an empty string.
// Example:
// reverseAlphabeticalOrder("") == ""
func reverseAlphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted().reversed())
}
// 8. Write a function that takes a string and returns a string with the letters in alphabetical order.
// If the string is empty, return an empty string.
// Example:
// alphabeticalOrder("") == ""
func alphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted())
}
// 9. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// If the string is empty, return an empty string.
// Example:
// reverseAlphabeticalOrder("") == ""
func reverseAlphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted().reversed())
}
// 10. Write a function that takes a string and returns a string with the letters in alphabetical order.
// If the string is empty, return an empty string.
// Example:
// alphabeticalOrder("") == ""
func alphabeticalOrder(str: String) -> String {
if str.isEmpty {
return ""
}
return String(str.map(Character.init).sorted())
}
// 11. Write a function that takes a string and returns a string with the letters in reverse alphabetical order.
// If the string is empty, return an empty string.
// Example
even += 1 // left side of mutating operator isn't mutable: 'even' is a 'let' constant
odd += 1 // left side of mutating operator isn't mutable: 'odd' is a 'let' constant
abs /= 10 // left side of mutating operator isn't mutable: 'abs' is a 'let' constant
func alphabeticalOrder(str: String) -> String { // invalid redeclaration of 'alphabeticalOrder(str:)'
func reverseAlphabeticalOrder(str: String) -> String { // invalid redeclaration of 'reverseAlphabeticalOrder(str:)'
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var absNum = abs(num)
while absNum > 0 {
if absNum % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
absNum /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var abs = abs(num)
while abs > 0 {
if abs % 2 == 0 {
even += 1
} else {
odd += 1
}
abs /= 10
}
return (even, odd)
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
func reverseString(string: String) -> String {
var result = ""
for char in string.reversed() {
result += String(char)
}
return result
}
func capitalizeString(string: String) -> String {
var result = ""
for char in string.capitalized {
result += String(char)
}
return result
}
func toLowercaseString(string: String) -> String {
var result = ""
for char in string.lowercased {
result += String(char)
}
return result
}
func toUppercaseString(string: String) -> String {
var result = ""
for char in string.uppercased {
result += String(char)
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 14. Write a function that takes a string as input and returns the string
// reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Greetings from Earth") == "htraE morf sgniteerG"
func reverseString(string: String) -> String {
var result = ""
for char in string.reversed() {
result += String(char)
}
return result
}
// -----------------------------------------------------------------------------
// 15. Write a function that takes a string as input and returns the string
// capitalized.
// Examples:
// capitalizeString("hello") == "Hello"
// capitalizeString("Greetings from Earth") == "Greetings from Earth"
func capitalizeString(string: String) -> String {
var result = ""
for char in string.capitalized {
result += String(char)
}
return result
}
// -----------------------------------------------------------------------------
// 16. Write a function that takes a string as input and returns the string
// converted to lowercase.
// Examples:
// toLowercaseString("Hello") == "hello"
// toLowercaseString("Greetings from Earth") == "greetings from earth"
func toLowercaseString(string: String) -> String {
var result = ""
for char in string.lowercased {
result += String(char)
}
return result
}
// -----------------------------------------------------------------------------
// 17. Write a function that takes a string as input and returns the string
// converted to uppercase.
// Examples:
// toUppercaseString("hello") == "HELLO"
// toUppercaseString("Greetings from Earth") == "GREETINGS FROM EARTH"
func toUppercaseString(string: String) -> String {
var result = ""
for char in string.uppercased {
result += String(char)
}
return result
}
// -----------------------------------------------------------------------------
// 18. Write a function that takes a string as input and returns the string
// converted to titlecase.
// Examples:
// toTitlecaseString("hello") == "Hello"
// toTitlecaseString("
for char in string.lowercased { // no 'lowercased' overloads produce result type that conforms to 'Sequence'
for char in string.uppercased { // no 'uppercased' overloads produce result type that conforms to 'Sequence'
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let romanNumeralArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let decimalNumbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<13 {
while number >= decimalNumbers[i] {
romanNumeral += romanNumeralArray[i]
number -= decimalNumbers[i]
}
}
return romanNumeral
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let romanNumeralArray = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let decimalNumbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
for i in 0..<13 {
while number >= decimalNumbers[i] {
romanNumeral += romanNumeralArray[i]
number -= decimalNumbers[i]
}
}
return romanNumeral
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given a string, determine if it is a palindrome, ignoring whitespace and
// punctuation.
// Examples:
// isPalindrome("A man, a plan, a canal: Panama") == true
// isPalindrome("race car") == true
// isPalindrome("not a palindrome") == false
// isPalindrome("no 'x' in 'abax'") == true
// isPalindrome("abba") == true
// isPalindrome("") == true
// isPalindrome("a.") == true
// isPalindrome("a.b") == false
// isPalindrome("a.b.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a") == true
// isPalindrome("a.b.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a.d.c.b.a
romanNumeral += romanNumeralArray[i] // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
number -= decimalNumbers[i] // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a string, return the string with all the vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prsn drnkng Dt Ck n scl."
// removeVowels("Why do you ask?") == " Why d y u sk?"
// removeVowels("A thing of beauty is a joy forever.") == " tnhg f bjry frys jry."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Given a string, return the string with all the vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prsn drnkng Dt Ck n scl."
// removeVowels("Why do you ask?") == " Why d y u sk?"
// removeVowels("A thing of beauty is a joy forever.") == " tnhg f bjry frys jry."
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Given a string, return the string with all the vowels removed.
// Examples:
// removeVowels("I have never seen a thin person drinking Diet Coke on a scale.") == " hv nvr sn thn prsn drnkng Dt Ck n scl."
// removeVowels("Why do you ask?") == " Why d y u sk?"
// removeVowels("A thing of beauty is a joy forever.") == " tnhg f bjry frys jry."
func removeVowels(input
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func intToMiniRoman(number: Int) -> String {
var roman = ""
if number >= 1000 {
roman += "m"
number -= 1000
}
if number >= 900 {
roman += "cm"
number -= 900
}
if number >= 500 {
roman += "d"
number -= 500
}
if number >= 400 {
roman += "cd"
number -= 400
}
if number >= 100 {
roman += "c"
number -= 100
}
if number >= 90 {
roman += "xc"
number -= 90
}
if number >= 50 {
roman += "l"
number -= 50
}
if number >= 40 {
roman += "xl"
number -= 40
}
if number >= 10 {
roman += "x"
number -= 10
}
if number == 9 {
roman += "ix"
number -= 9
}
if number >= 5 {
roman += "v"
number -= 5
}
if number == 4 {
roman += "iv"
number -= 4
}
if number >= 1 {
roman += "i"
number -= 1
}
return roman
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var roman = ""
if number >= 1000 {
roman += "m"
number -= 1000
}
if number >= 900 {
roman += "cm"
number -= 900
}
if number >= 500 {
roman += "d"
number -= 500
}
if number >= 400 {
roman += "cd"
number -= 400
}
if number >= 100 {
roman += "c"
number -= 100
}
if number >= 90 {
roman += "xc"
number -= 90
}
if number >= 50 {
roman += "l"
number -= 50
}
if number >= 40 {
roman += "xl"
number -= 40
}
if number >= 10 {
roman += "x"
number -= 10
}
if number == 9 {
roman += "ix"
number -= 9
}
if number >= 5 {
roman += "v"
number -= 5
}
if number == 4 {
roman += "iv"
number -= 4
}
if number >= 1 {
roman += "i"
number -= 1
}
return roman
}
// -----------------------------------------------------------------------------
// 10. Given a string, determine if it is a palindrome, ignoring all non-alphanumeric
// characters and ignoring case.
// Examples:
// isPalindrome("A man, a plan, a canal: Panama") == true
// isPalindrome("race car") == true
// isPalindrome("not a palindrome") == false
// isPalindrome("") == true
// isPalindrome(" ") == true
// isPalindrome("a.") == true
// isPalindrome("a.a") == true
// isPalindrome("a.a.a") == true
// isPalindrome("a.a.a.a") == true
// isPalindrome("a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a") == true
// isPalindrome("a.a.a.a.
number -= 1000 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 900 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 500 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 400 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 100 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 90 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 50 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 40 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 10 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 9 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 5 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 4 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
number -= 1 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let num = number
while num > 0 {
if num >= 1000 {
romanNumeral += "m"
num -= 1000
} else if num >= 900 {
romanNumeral += "cm"
num -= 900
} else if num >= 500 {
romanNumeral += "d"
num -= 500
} else if num >= 400 {
romanNumeral += "cd"
num -= 400
} else if num >= 100 {
romanNumeral += "c"
num -= 100
} else if num >= 90 {
romanNumeral += "xc"
num -= 90
} else if num >= 50 {
romanNumeral += "l"
num -= 50
} else if num >= 40 {
romanNumeral += "xl"
num -= 40
} else if num >= 10 {
romanNumeral += "x"
num -= 10
} else if num >= 9 {
romanNumeral += "ix"
num -= 9
} else if num >= 5 {
romanNumeral += "v"
num -= 5
} else if num >= 4 {
romanNumeral += "iv"
num -= 4
} else if num >= 1 {
romanNumeral += "i"
num -= 1
}
}
return romanNumeral
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let num = number
while num > 0 {
if num >= 1000 {
romanNumeral += "m"
num -= 1000
} else if num >= 900 {
romanNumeral += "cm"
num -= 900
} else if num >= 500 {
romanNumeral += "d"
num -= 500
} else if num >= 400 {
romanNumeral += "cd"
num -= 400
} else if num >= 100 {
romanNumeral += "c"
num -= 100
} else if num >= 90 {
romanNumeral += "xc"
num -= 90
} else if num >= 50 {
romanNumeral += "l"
num -= 50
} else if num >= 40 {
romanNumeral += "xl"
num -= 40
} else if num >= 10 {
romanNumeral += "x"
num -= 10
} else if num >= 9 {
romanNumeral += "ix"
num -= 9
} else if num >= 5 {
romanNumeral += "v"
num -= 5
} else if num >= 4 {
romanNumeral += "iv"
num -= 4
} else if num >= 1 {
romanNumeral += "i"
num -= 1
}
}
return romanNumeral
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
//
romanNumeral += "m" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 1000 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "cm" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 900 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "d" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 500 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "cd" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 400 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "c" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 100 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "xc" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 90 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "l" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 50 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "xl" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 40 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "x" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 10 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "ix" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 9 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "v" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 5 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "iv" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 4 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "i" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 1 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "A" && char != "E" && char != "I" && char != "O" && char != "U" {
result += char
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples:
// removeVowels("Hello, world!") == "Hll, wrld!"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "A" && char != "E" && char != "I" && char != "O" && char != "U" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples:
// removeVowels("Hello, world!") == "Hll, wrld!"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" && char != "A" && char != "E" && char != "I" && char != "O" && char != "U" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a string as input and returns the string
// with all the vowels removed.
// Examples:
// removeVowels("Hello, world!") == "Hll, wrld!"
// removeVowels("aeiou") == ""
// removeVowels("") == ""
// removeVowels("aeiouAEIOU") == ""
func removeVowels(input:
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
func reverseString(string: String) -> String {
return string.reversed().join("")
}
func countBits(number: Int) -> Int {
var count = 0
var num = number
while num > 0 {
if num & 1 == 1 {
count += 1
}
num >>= 1
}
return count
}
func factorialTrailingZeroes(number: Int) -> Int {
var count = 0
var num = number
while num > 0 {
count += num / 5
num /= 5
}
return count
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result += "m"
num -= 1000
} else if num >= 900 {
result += "cm"
num -= 900
} else if num >= 500 {
result += "d"
num -= 500
} else if num >= 400 {
result += "cd"
num -= 400
} else if num >= 100 {
result += "c"
num -= 100
} else if num >= 90 {
result += "xc"
num -= 90
} else if num >= 50 {
result += "l"
num -= 50
} else if num >= 40 {
result += "xl"
num -= 40
} else if num >= 10 {
result += "x"
num -= 10
} else if num >= 9 {
result += "ix"
num -= 9
} else if num >= 5 {
result += "v"
num -= 5
} else if num >= 4 {
result += "iv"
num -= 4
} else if num >= 1 {
result += "i"
num -= 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as input, and returns the string
// reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Greetings!") == "!sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join("")
}
// -----------------------------------------------------------------------------
// 11. Write a function that takes an integer as input, and returns the number of
// bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function
// should return 5 in this case
// Examples:
// countBits(number: 1234) == 5
// countBits(number: 7) == 3
// countBits(number: 9) == 2
// countBits(number: 10) == 2
func countBits(number: Int) -> Int {
var count = 0
var num = number
while num > 0 {
if num & 1 == 1 {
count += 1
}
num >>= 1
}
return count
}
// -----------------------------------------------------------------------------
// 12. Write a function that takes a number as input, and returns the number of
// trailing zeroes in the factorial of that number.
// Examples:
// factorialTrailingZeroes(number: 3) == 0
// factorialTrailingZeroes(number: 5) == 1
// factorialTrailingZeroes(number: 10) == 2
// factorialTrailingZeroes(number: 15) == 3
func factorialTrailingZeroes(number: Int) -> Int {
var count = 0
var num = number
while num > 0 {
count += num / 5
num /= 5
}
return count
}
// -----------------------------------------------------------------------------
// 13. Write a function that takes a string as input, and returns the string
// reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Greetings!") == "!sgniteerG"
func reverseString(string: String) -> String {
return string
return string.reversed().join("") // reference to member 'join' cannot be resolved without a contextual type
func intToMiniRoman(number: Int) -> String {
let roman = [
["i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"],
["x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"],
["c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"],
["m", "mm", "mmm", "", "", "", "", "", ""]
]
var result = ""
for i in 0..<3 {
let num = number % 10
result = roman[i][num] + result
number /= 10
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let roman = [
["i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"],
["x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"],
["c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"],
["m", "mm", "mmm", "", "", "", "", "", ""]
]
var result = ""
for i in 0..<3 {
let num = number % 10
result = roman[i][num] + result
number /= 10
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------
number /= 10 // left side of mutating operator isn't mutable: 'number' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let num = number
while num > 0 {
if num >= 1000 {
romanNumeral += "m"
num -= 1000
} else if num >= 900 {
romanNumeral += "cm"
num -= 900
} else if num >= 500 {
romanNumeral += "d"
num -= 500
} else if num >= 400 {
romanNumeral += "cd"
num -= 400
} else if num >= 100 {
romanNumeral += "c"
num -= 100
} else if num >= 90 {
romanNumeral += "xc"
num -= 90
} else if num >= 50 {
romanNumeral += "l"
num -= 50
} else if num >= 40 {
romanNumeral += "xl"
num -= 40
} else if num >= 10 {
romanNumeral += "x"
num -= 10
} else if num >= 9 {
romanNumeral += "ix"
num -= 9
} else if num >= 5 {
romanNumeral += "v"
num -= 5
} else if num >= 4 {
romanNumeral += "iv"
num -= 4
} else if num >= 1 {
romanNumeral += "i"
num -= 1
}
}
return romanNumeral
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumeral = ""
let num = number
while num > 0 {
if num >= 1000 {
romanNumeral += "m"
num -= 1000
} else if num >= 900 {
romanNumeral += "cm"
num -= 900
} else if num >= 500 {
romanNumeral += "d"
num -= 500
} else if num >= 400 {
romanNumeral += "cd"
num -= 400
} else if num >= 100 {
romanNumeral += "c"
num -= 100
} else if num >= 90 {
romanNumeral += "xc"
num -= 90
} else if num >= 50 {
romanNumeral += "l"
num -= 50
} else if num >= 40 {
romanNumeral += "xl"
num -= 40
} else if num >= 10 {
romanNumeral += "x"
num -= 10
} else if num >= 9 {
romanNumeral += "ix"
num -= 9
} else if num >= 5 {
romanNumeral += "v"
num -= 5
} else if num >= 4 {
romanNumeral += "iv"
num -= 4
} else if num >= 1 {
romanNumeral += "i"
num -= 1
}
}
return romanNumeral
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------
romanNumeral += "m" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 1000 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "cm" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 900 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "d" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 500 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "cd" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 400 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "c" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 100 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "xc" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 90 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "l" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 50 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "xl" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 40 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "x" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 10 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "ix" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 9 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "v" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 5 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "iv" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 4 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanNumeral += "i" // left side of mutating operator isn't mutable: 'romanNumeral' is a 'let' constant
num -= 1 // left side of mutating operator isn't mutable: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let roman = ["i", "v", "x", "l", "c", "d", "m"]
var result = ""
for i in 0..<7 {
let digit = number % 10
if digit == 0 {
continue
}
if digit < 4 {
for _ in 0..<digit {
result = roman[i] + result
}
} else if digit == 4 {
result = roman[i] + roman[i + 1] + result
} else if digit < 9 {
result = roman[i + 1] + (digit - 5) * roman[i] + result
} else {
result = roman[i] + roman[i + 2] + result
}
number /= 10
}
return result
}
func reverseString(string: String) -> String {
return string.reversed().join()
}
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
count += number & 1
number >>= 1
}
return count
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let roman = ["i", "v", "x", "l", "c", "d", "m"]
var result = ""
for i in 0..<7 {
let digit = number % 10
if digit == 0 {
continue
}
if digit < 4 {
for _ in 0..<digit {
result = roman[i] + result
}
} else if digit == 4 {
result = roman[i] + roman[i + 1] + result
} else if digit < 9 {
result = roman[i + 1] + (digit - 5) * roman[i] + result
} else {
result = roman[i] + roman[i + 2] + result
}
number /= 10
}
return result
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string as input and returns the string reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Greetings!") == "!sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes an integer as input, and returns the number of
// bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function
// should return 5 in this case
// Examples:
// countBits(number: 1234) == 5
// countBits(number: 7) == 3
// countBits(number: 9) == 2
// countBits(number: 10) == 2
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
count += number & 1
number >>= 1
}
return count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the string
// reversed.
// Examples:
// reverseString("hello") == "olleh"
// reverseString("Greetings!") == "!sgniteerG"
func reverseString(string: String) -> String {
return string.reversed().join()
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes an integer as input, and returns the number of
// bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function
// should return 5 in this case
// Examples:
// countBits(number: 1234) == 5
// countBits(number: 7) == 3
// countBits(number: 9) == 2
// countBits(number: 10) == 2
func countBits(number: Int) -> Int {
var count = 0
while number > 0 {
count += number & 1
number >>= 1
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes an integer as input, and returns the number of
// bits that are equal to one in the binary representation of that number.
// Example: The binary representation of 1234 is 10011010010, so the function
// should return 5 in this case
// Examples:
// countBits(number: 1234) == 5
// countBits(number:
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
return aSquared + bSquared == cSquared ||
aSquared + cSquared == bSquared ||
bSquared + cSquared == aSquared
}
func countVowels(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
func countConsonants(s: String) -> Int {
let consonants = "bcdfghjklmnpqrstvwxyz"
var count = 0
for char in s {
if consonants.contains(char) {
count += 1
}
}
return count
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char.isUpper {
count += 1
}
}
return count
}
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char.isLower {
count += 1
}
}
return count
}
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
return aSquared + bSquared == cSquared ||
aSquared + cSquared == bSquared ||
bSquared + cSquared == aSquared
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number (count) of vowels
// in the string.
// Example:
// countVowels("apple") == 2
// countVowels("hello") == 2
// countVowels("why") == 0
func countVowels(s: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number (count) of
// consonants in the string.
// Example:
// countConsonants("apple") == 3
// countConsonants("hello") == 3
// countConsonants("why") == 0
func countConsonants(s: String) -> Int {
let consonants = "bcdfghjklmnpqrstvwxyz"
var count = 0
for char in s {
if consonants.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number (count) of
// uppercase letters in the string.
// Example:
// countUppercase("apple") == 1
// countUppercase("hello") == 1
// countUppercase("why") == 0
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char.isUpper {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number (count) of
// lowercase letters in the string.
// Example:
// countLowercase("apple") == 5
// countLowercase("hello") == 5
// countLowercase("why") == 2
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char.isLower {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number (count) of
// digits in the string.
// Example:
// countDigits("apple") == 0
// countDigits("hello") == 0
// countDigits("why") == 1
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number (count) of
// whitespace characters in the string.
// Example:
// countWhitespace("apple") == 0
// countWhitespace("hello") == 1
// count
if char.isUpper { // value of type 'Character' has no member 'isUpper'
if char.isLower { // value of type 'Character' has no member 'isLower'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
return aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared
}
func countVowels(string: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
func countConsonants(string: String) -> Int {
let consonants = "bcdfghjklmnpqrstvwxyz"
var count = 0
for char in string {
if consonants.contains(char) {
count += 1
}
}
return count
}
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
func countSentences(string: String) -> Int {
return string.split(separator: ". ").count
}
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit() {
count += 1
}
}
return count
}
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper() {
count += 1
}
}
return count
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
return aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as input and returns the number of
// vowels in the string.
// Example:
// countVowels("Hello") == 2
// countVowels("apple") == 2
func countVowels(string: String) -> Int {
let vowels = "aeiou"
var count = 0
for char in string {
if vowels.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as input and returns the number of
// consonants in the string.
// Example:
// countConsonants("Hello") == 3
// countConsonants("apple") == 5
func countConsonants(string: String) -> Int {
let consonants = "bcdfghjklmnpqrstvwxyz"
var count = 0
for char in string {
if consonants.contains(char) {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as input and returns the number of
// words in the string.
// Example:
// countWords("Hello world") == 2
// countWords("apple") == 1
func countWords(string: String) -> Int {
return string.split(separator: " ").count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as input and returns the number of
// sentences in the string.
// Example:
// countSentences("Hello world. How are you?") == 2
// countSentences("apple") == 0
func countSentences(string: String) -> Int {
return string.split(separator: ". ").count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string as input and returns the number of
// digits in the string.
// Example:
// countDigits("Hello123") == 3
// countDigits("apple") == 0
func countDigits(string: String) -> Int {
var count = 0
for char in string {
if char.isDigit() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 7. Write a function that takes a string as input and returns the number of
// uppercase letters in the string.
// Example:
// countUppercase("Hello") == 1
// countUppercase("apple") == 0
func countUppercase(string: String) -> Int {
var count = 0
for char in string {
if char.isUpper() {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 8. Write a function that takes a string as input and returns the number of
// lowercase letters in the string.
// Example:
// countLowercase("Hello") == 4
// countLowercase("apple") == 5
func
if char.isDigit() { // value of type 'Character' has no member 'isDigit'
if char.isUpper() { // value of type 'Character' has no member 'isUpper'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
func countWords(s: String) -> Int {
return s.split(separator: " ").count
}
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
// -----------------------------------------------------------------------------
// 1. Write a function that takes a string and returns the number of vowels
// contained in the string.
// Example:
// countVowels("Hello World") == 3
// countVowels("aeiou") == 5
// countVowels("") == 0
func countVowels(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns the number of words
// contained in the string.
// Example:
// countWords("Hello World") == 2
// countWords("Hello") == 1
// countWords("") == 0
func countWords(s: String) -> Int {
return s.split(separator: " ").count
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns the number of uppercase
// letters contained in the string.
// Example:
// countUppercase("Hello World") == 2
// countUppercase("Hello") == 0
// countUppercase("") == 0
func countUppercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.uppercase {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns the number of lowercase
// letters contained in the string.
// Example:
// countLowercase("Hello World") == 5
// countLowercase("Hello") == 5
// countLowercase("") == 0
func countLowercase(s: String) -> Int {
var count = 0
for char in s {
if char == char.lowercase {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns the number of digits
// contained in the string.
// Example:
// countDigits("Hello World") == 0
// countDigits("Hello") == 0
// countDigits("") == 0
// countDigits("12345") == 5
func countDigits(s: String) -> Int {
var count = 0
for char in s {
if char.isDigit {
count += 1
}
}
return count
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns the number of words
// that start with a vowel.
// Example:
// countWordsStartingWithVowel("Hello World") == 1
// countWordsStartingWithVowel("Hello") == 1
// countWordsStartingWithVowel("") == 0
// countWordsStartingWithVowel("apple") == 1
func countWordsStartingWithVowel(s: String) -> Int {
var count = 0
for word in s.split(separator: " ") {
if word.first == "a" || word.first == "e" || word.first == "i" || word.first == "o" || word.first == "u
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
func longestSubstringWithoutRepeatingCharacters(s: String) -> Int {
var max = 0
var start = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] != nil {
start = max(map[s[i]], start)
}
map[s[i]] = i + 1
max = max(max, i - start + 1)
}
return max
}
func maxSubArray(nums: [Int]) -> Int {
var max = nums[0]
var sum = 0
for i in 0..<nums.count {
if sum < 0 {
sum = 0
}
sum += nums[i]
max = max(max, sum)
}
return max
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given a string, return the length of the longest substring without repeating
// characters.
// Example:
// longestSubstringWithoutRepeatingCharacters("abcabcbb") == 3
// longestSubstringWithoutRepeatingCharacters("bbbbb") == 1
// longestSubstringWithoutRepeatingCharacters("pwwkew") == 3
func longestSubstringWithoutRepeatingCharacters(s: String) -> Int {
var max = 0
var start = 0
var map = [Int: Int]()
for i in 0..<s.count {
if map[s[i]] != nil {
start = max(map[s[i]], start)
}
map[s[i]] = i + 1
max = max(max, i - start + 1)
}
return max
}
// -----------------------------------------------------------------------------
// 1.2
// -----------------------------------------------------------------------------
// Given an array of integers, return the maximum sum for a contiguous subarray
// of the array.
// Example:
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([1, 2, 3]) == 6
// maxSubArray([-1, -2, -3]) == -1
func maxSubArray(nums: [Int]) -> Int {
var max = nums[0]
var sum = 0
for i in 0..<nums.count {
if sum < 0 {
sum = 0
}
sum += nums[i]
max = max(max, sum)
}
return max
}
// -----------------------------------------------------------------------------
// 1.3
// -----------------------------------------------------------------------------
// Given an array of integers, return the maximum sum for a contiguous subarray
// of the array.
// Example:
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([1, 2, 3]) == 6
// maxSubArray([-1, -2, -3]) == -1
func maxSubArray(nums: [Int]) -> Int {
var max = nums[0]
var sum = 0
for i in 0..<nums.count {
if sum < 0 {
sum = 0
}
sum += nums[i]
max = max(max, sum)
}
return max
}
// -----------------------------------------------------------------------------
// 1.4
// -----------------------------------------------------------------------------
// Given an array of integers, return the maximum sum for a contiguous subarray
// of the array.
// Example:
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
// maxSubArray([1, 2, 3]) == 6
// maxSubArray([-1, -2, -3]) == -1
func maxSubArray(nums: [Int]) -> Int {
var max =
if map[s[i]] != nil { // cannot convert value of type 'Character' to expected argument type 'Int'
start = max(map[s[i]], start) // cannot call value of non-function type 'Int'
start = max(map[s[i]], start) // no exact matches in call to subscript
map[s[i]] = i + 1 // cannot convert value of type 'Character' to expected argument type 'Int'
max = max(max, i - start + 1) // cannot call value of non-function type 'Int'
max = max(max, sum) // cannot call value of non-function type 'Int'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared {
return true
} else {
return false
}
}
func countVowels(input: String) -> Int {
var count = 0
for char in input {
switch char {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
func countConsonants(input: String) -> Int {
var count = 0
for char in input {
switch char {
case "a", "e", "i", "o", "u":
break
default:
count += 1
}
}
return count
}
func countWords(input: String) -> Int {
var count = 0
for char in input {
if char == " " {
count += 1
}
}
return count + 1
}
func countUppercase(input: String) -> Int {
var count = 0
for char in input {
if char == char.uppercase {
count += 1
}
}
return count
}
func countLowercase(input: String) -> Int {
var count = 0
for char in input {
if char == char.lowercase {
count += 1
}
}
return count
}
func countDigits(input: String) -> Int {
var count = 0
for char in input {
if char.isdigit {
count += 1
}
}
return count
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
let aSquared = a * a
let bSquared = b * b
let cSquared = c * c
if aSquared + bSquared == cSquared || aSquared + cSquared == bSquared || bSquared + cSquared == aSquared {
return true
} else {
return false
}
}
// 10. Write a function that takes a string as input and returns the number of
// vowels in the string.
// Example:
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
func countVowels(input: String) -> Int {
var count = 0
for char in input {
switch char {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
// 11. Write a function that takes a string as input and returns the number of
// consonants in the string.
// Example:
// countConsonants("Hello world") == 5
// countConsonants("aeiou") == 0
func countConsonants(input: String) -> Int {
var count = 0
for char in input {
switch char {
case "a", "e", "i", "o", "u":
break
default:
count += 1
}
}
return count
}
// 12. Write a function that takes a string as input and returns the number of
// words in the string.
// Example:
// countWords("Hello world") == 2
// countWords("Hello world!") == 2
func countWords(input: String) -> Int {
var count = 0
for char in input {
if char == " " {
count += 1
}
}
return count + 1
}
// 13. Write a function that takes a string as input and returns the number of
// uppercase letters in the string.
// Example:
// countUppercase("Hello world") == 2
// countUppercase("hello world") == 0
func countUppercase(input: String) -> Int {
var count = 0
for char in input {
if char == char.uppercase {
count += 1
}
}
return count
}
// 14. Write a function that takes a string as input and returns the number of
// lowercase letters in the string.
// Example:
// countLowercase("Hello world") == 5
// countLowercase("HELLO WORLD") == 0
func countLowercase(input: String) -> Int {
var count = 0
for char in input {
if char == char.lowercase {
count += 1
}
}
return count
}
// 15. Write a function that takes a string as input and returns the number of
// digits in the string.
// Example:
// countDigits("Hello world") == 0
// countDigits("12345") == 5
func countDigits(input: String) -> Int {
var count = 0
for char in input {
if char.isdigit {
count += 1
}
}
return count
}
// 16. Write a function that takes a string as input and returns the number of
// vowels in the string.
// Example:
// countVowels("Hello world") == 3
// countVowels("aeiou") == 5
func countVowels(input: String) -> Int {
var count = 0
for char in input {
switch char {
case "a", "e", "i", "o", "u":
count += 1
default:
break
}
}
return count
}
// 17. Write a function that takes a string as input and returns
if char == char.uppercase { // value of type 'Character' has no member 'uppercase'
if char == char.lowercase { // value of type 'Character' has no member 'lowercase'
if char.isdigit { // value of type 'Character' has no member 'isdigit'
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
// -----------------------------------------------------------------------------
// 1.1.1.1.2.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1.1
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
func isPalindromeIgnoringCaseAndNonLetters(s: String) -> Bool {
return s == String(s.reversed()) || s == String(s.reversed().reversed())
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c
}
// -----------------------------------------------------------------------------
// 1.10
// Given a string, return true if the string is a palindrome, and false
// otherwise.
// A palindrome is a string that's the same forwards and backwards.
// Example:
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// -----------------------------------------------------------------------------
// 1.11
// Given a string, return true if the string is a palindrome, ignoring
// case and non-letter characters.
// A palindrome is a string that's the same forwards and backwards.
// Example:
// isPalindromeIgnoringCaseAndNonLetters("racecar") == true
// isPalindromeIgnoringCaseAndNonLetters("hello") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam, I'm Adam!") == false
func isPalindromeIgnoringCaseAndNonLetters(s: String) -> Bool {
return s == String(s.reversed()) || s == String(s.reversed().reversed())
}
// -----------------------------------------------------------------------------
// 1.12
// Given a string, return true if the string is a palindrome, ignoring
// case and non-letter characters.
// A palindrome is a string that's the same forwards and backwards.
// Example:
// isPalindromeIgnoringCaseAndNonLetters("racecar") == true
// isPalindromeIgnoringCaseAndNonLetters("hello") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam, I'm Adam!") == false
func isPalindromeIgnoringCaseAndNonLetters(s: String) -> Bool {
return s == String(s.reversed()) || s == String(s.reversed().reversed())
}
// -----------------------------------------------------------------------------
// 1.13
// Given a string, return true if the string is a palindrome, ignoring
// case and non-letter characters.
// A palindrome is a string that's the same forwards and backwards.
// Example:
// isPalindromeIgnoringCaseAndNonLetters("racecar") == true
// isPalindromeIgnoringCaseAndNonLetters("hello") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam!") == true
// isPalindromeIgnoringCaseAndNonLetters("Madam, I'm Adam, I'm Adam, I'm Adam!") == false
func isPalindromeIgnoringCaseAndNonLetters(s: String) -> Bool {
return s == String(s.reversed()) || s == String(s.reversed().reversed())
}
// -----------------------------------------------------------------------------
// 1.14
// Given a string, return true if the string is a pal
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
// -----------------------------------------------------------------------------
// 1.1.2
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 1.1.3
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 1.1.4
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 1.1.5
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 1.1.6
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0 + $1 })
}
// -----------------------------------------------------------------------------
// 1.1.7
// -----------------------------------------------------------------------------
// Given an array of integers, return the sum of all the positive integers in the
// array.
// Example:
// sumPositives([1, 2, 3, -1, 5, -8, 0]) == 9
func sumPositives(numbers: [Int]) -> Int {
return numbers.filter( { $0 > 0 } ).reduce(0, { $0
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
func sumNumbers(s: String) -> Int {
var sum = 0
var i = 0
while i < s.count {
if CharacterSet.numbers.contains(s[i]) {
var num = 0
while i < s.count && CharacterSet.numbers.contains(s[i]) {
num = num * 10 + Int(s[i] - '0')
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return (a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
}
// -----------------------------------------------------------------------------
// 11. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var i = 0
while i < s.count {
if CharacterSet.numbers.contains(s[i]) {
var num = 0
while i < s.count && CharacterSet.numbers.contains(s[i]) {
num = num * 10 + Int(s[i] - '0')
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
// -----------------------------------------------------------------------------
// 12. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var i = 0
while i < s.count {
if CharacterSet.numbers.contains(s[i]) {
var num = 0
while i < s.count && CharacterSet.numbers.contains(s[i]) {
num = num * 10 + Int(s[i] - '0')
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
// -----------------------------------------------------------------------------
// 13. Given a string, return the sum of the numbers appearing in the string,
// ignoring all other characters. A number is a series of 1 or more digit
// characters in a row. (Note: Character.isDigit(char) tests if a char is one
// of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an
// int.)
// Example:
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var sum = 0
var i = 0
while i < s.count {
if CharacterSet.numbers.contains(s[i]) {
var num = 0
while i < s.count && CharacterSet.numbers.contains(s[i]) {
num = num * 10 + Int(s[i] - '0')
i += 1
}
sum += num
} else {
i += 1
}
}
return sum
}
if CharacterSet.numbers.contains(s[i]) { // type 'CharacterSet' has no member 'numbers'
while i < s.count && CharacterSet.numbers.contains(s[i]) { // type 'CharacterSet' has no member 'numbers'
num = num * 10 + Int(s[i] - '0') // binary operator '-' cannot be applied to operands of type 'Character' and 'String'
num = num * 10 + Int(s[i] - '0') // single-quoted string literal found, use '"'
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
var temp = ""
for char in word {
if temp.contains(char) {
continue
}
temp += char
count += 1
}
if count > max {
max = count
result = word
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
var temp = ""
for char in word {
if temp.contains(char) {
continue
}
temp += char
count += 1
}
if count > max {
max = count
result = word
}
}
return result
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
temp += char // cannot convert value of type 'Character' to expected argument type 'String'
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
// -----------------------------------------------------------------------------
// 1.1
// Write a function that accepts an array of integers.
// The array contains different numbers. Return the number which is
// closest to zero. If multiple numbers are closest to zero, return the
// one which comes first in lexicographical order.
// findClosest(numbers: [1, 2, 3, 4, 5]) == 1
// findClosest(numbers: [1, 2, 3, 4, 5, -1]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14]) == -1
// findClosest(numbers: [1, 2, 3, 4, 5, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15]) == -1
// findClosest(numbers: [1,
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
var temp = ""
for char in word {
if !temp.contains(char) {
temp += char
unique += 1
}
}
if max.isEmpty || max.count < unique {
max = temp
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
var temp = ""
for char in word {
if !temp.contains(char) {
temp += char
unique += 1
}
}
if max.isEmpty || max.count < unique {
max = temp
}
}
return max
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
temp += char // cannot convert value of type 'Character' to expected argument type 'String'
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
var arr = [Int]()
for char in word {
if !arr.contains(Int(char)) {
arr.append(Int(char))
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func average(numbers: [Int]) -> Double {
var sum = 0
for number in numbers {
sum += number
}
return Double(sum) / Double(numbers.count)
}
func product(numbers: [Int]) -> Int {
var product = 1
for number in numbers {
product *= number
}
return product
}
func largest(numbers: [Int]) -> Int {
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func smallest(numbers: [Int]) -> Int {
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
var count = 0
var arr = [Int]()
for char in word {
if !arr.contains(Int(char)) {
arr.append(Int(char))
count += 1
}
}
if count > max {
max = count
result = word
}
}
return result
}
print(findMax(words: ["name", "of", "string"]))
print(findMax(words: ["name", "enam", "game"]))
print(findMax(words: ["aaaaaaa", "bb", "cc"]))<|endoftext|>// 1. Write a function that accepts an array of integers and returns the sum of all the integers.
// sum([1,2,3,4,5]) == 15
// sum([1,2,3,4,5,6,7,8,9,10]) == 55
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
print(sum([1,2,3,4,5]))
print(sum([1,2,3,4,5,6,7,8,9,10]))
// 2. Write a function that accepts an array of integers and returns the average of all the integers.
// average([1,2,3,4,5]) == 3
// average([1,2,3,4,5,6,7,8,9,10]) == 6.5
func average(numbers: [Int]) -> Double {
var sum = 0
for number in numbers {
sum += number
}
return Double(sum) / Double(numbers.count)
}
print(average([1,2,3,4,5]))
print(average([1,2,3,4,5,6,7,8,9,10]))
// 3. Write a function that accepts an array of integers and returns the product of all the integers.
// product([1,2,3,4,5]) == 120
// product([1,2,3,4,5,6,7,8,9,10]) == 3628800
func product(numbers: [Int]) -> Int {
var product = 1
for number in numbers {
product *= number
}
return product
}
print(product([1,2,3,4,5]))
print(product([1,2,3,4,5,6,7,8,9,10]))
// 4. Write a function that accepts an array of integers and returns the largest integer.
// largest([1,2,3,4,5]) == 5
// largest([1,2,3,4,5,6,7,8,9,10]) == 10
func largest(numbers: [Int]) -> Int {
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
print(largest([1,2,3,4,5]))
print(largest([1,2,3,4,5,6,7,8,9,10]))
// 5. Write a function that accepts an array of integers and returns the smallest integer.
// smallest([1,2,3,4,5]) == 1
// smallest([1,2,3,4,5,6,7,8,9,10]) == 1
func smallest(numbers: [Int]) -> Int {
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
print(smallest([1,2,3,4,5]))
print(smallest([1,2,3,4,5,6,7,8,9,10]))
// 6. Write a function that accepts an array of integers and returns the sum of all the even integers.
// sumOfEven([1,2,3,4,5]) == 6
if !arr.contains(Int(char)) { // no exact matches in call to initializer
arr.append(Int(char)) // no exact matches in call to initializer
func findMax(words: [String]) -> String {
let max = words.first!
for word in words {
if word.count > max.count {
max = word
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
let max = words.first!
for word in words {
if word.count > max.count {
max = word
}
}
return max
}
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
max = word // cannot assign to value: 'max' is a 'let' constant
func findMax(words: [String]) -> String {
var max = ""
for word in words {
if word.count > max.count {
max = word
}
}
return max
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func sumGreaterThanAverage(numbers: [Int]) -> Int {
var sum = 0
var average = 0
for number in numbers {
sum += number
}
average = sum / numbers.count
var sumGreater = 0
for number in numbers {
if number > average {
sumGreater += number
}
}
return sumGreater
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
for word in words {
if word.count > max.count {
max = word
}
}
return max
}
// -----------------------------------------------------------------------------
// 1. Write a function that accepts an array of integers.
// The array contains different integers. Return the sum of all integers.
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 4]) == 10
// sum(numbers: [1, 2, 3, 4, 5]) == 15
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// -----------------------------------------------------------------------------
// 2. Write a function that accepts an array of integers.
// The array contains different integers. Return the sum of all integers
// that are greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 9
func sumGreaterThanAverage(numbers: [Int]) -> Int {
var sum = 0
var average = 0
for number in numbers {
sum += number
}
average = sum / numbers.count
var sumGreater = 0
for number in numbers {
if number > average {
sumGreater += number
}
}
return sumGreater
}
// -----------------------------------------------------------------------------
// 3. Write a function that accepts an array of integers.
// The array contains different integers. Return the sum of all integers
// that are greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 9
func sumGreaterThanAverage(numbers: [Int]) -> Int {
var sum = 0
var average = 0
for number in numbers {
sum += number
}
average = sum / numbers.count
var sumGreater = 0
for number in numbers {
if number > average {
sumGreater += number
}
}
return sumGreater
}
// -----------------------------------------------------------------------------
// 4. Write a function that accepts an array of integers.
// The array contains different integers. Return the sum of all integers
// that are greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 9
func sumGreaterThanAverage(numbers: [Int]) -> Int {
var sum = 0
var average = 0
for number in numbers {
sum += number
}
average = sum / numbers.count
var sumGreater = 0
for number in numbers {
if number > average {
sumGreater += number
}
}
return sumGreater
}
// -----------------------------------------------------------------------------
// 5. Write a function that accepts an array of integers.
// The array contains different integers. Return the sum of all integers
// that are greater than the average of all integers.
//
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
for char in word {
if word.count(char) == 1 {
unique += 1
}
}
if unique > max.count {
max = word
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
for char in word {
if word.count(char) == 1 {
unique += 1
}
}
if unique > max.count {
max = word
}
}
return max
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if word.count(char) == 1 { // cannot call value of non-function type 'Int'
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
var maxCount = 0
for word in words {
var count = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
count += 1
}
}
if count > maxCount {
max = word
maxCount = count
}
}
return max
}
print(findMax(words: ["name", "of", "string"]))
print(findMax(words: ["name", "enam", "game"]))
print(findMax(words: ["aaaaaaa", "bb", "cc"]))<|endoftext|>// 1. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 2. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 3. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 4. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 5. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 6. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 7. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 8. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 9. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 10. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 11. Write a function that accepts a string and returns the number (count)
// of vowels contained within it.
// countVowels("Celebration") == 5
// countVowels("Palm") == 1
// countVowels("Prediction") == 4
// 12.
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
let sorted = words.sorted(by: { (lhs: String, rhs: String) -> Bool in
return lhs.count > rhs.count
})
return sorted.first!
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
func sumGreaterThanAverage(numbers: [Int]) -> Int {
let average = numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
}) / numbers.count
return numbers.filter { $0 > average }.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
let sorted = words.sorted(by: { (lhs: String, rhs: String) -> Bool in
return lhs.count > rhs.count
})
return sorted.first!
}
// 2. Write a function that accepts an array of integers.
// The array contains integers. Return the sum of all integers.
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 4]) == 10
// sum(numbers: [1, 2, 3, 4, 5]) == 15
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
// 3. Write a function that accepts an array of integers.
// The array contains integers. Return the sum of all integers that are
// greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 6
func sumGreaterThanAverage(numbers: [Int]) -> Int {
let average = numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
}) / numbers.count
return numbers.filter { $0 > average }.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
// 4. Write a function that accepts an array of integers.
// The array contains integers. Return the sum of all integers that are
// greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 6
func sumGreaterThanAverage(numbers: [Int]) -> Int {
let average = numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
}) / numbers.count
return numbers.filter { $0 > average }.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
// 5. Write a function that accepts an array of integers.
// The array contains integers. Return the sum of all integers that are
// greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 6
func sumGreaterThanAverage(numbers: [Int]) -> Int {
let average = numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
}) / numbers.count
return numbers.filter { $0 > average }.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
})
}
// 6. Write a function that accepts an array of integers.
// The array contains integers. Return the sum of all integers that are
// greater than the average of all integers.
// sumGreaterThanAverage(numbers: [1, 2, 3]) == 0
// sumGreaterThanAverage(numbers: [1, 2, 3, 4]) == 4
// sumGreaterThanAverage(numbers: [1, 2, 3, 4, 5]) == 6
func sumGreaterThanAverage(numbers: [Int]) -> Int {
let average = numbers.reduce(0, { (sum: Int, number: Int) -> Int in
return sum + number
}) / numbers.count
return numbers.filter { $0 > average }.reduce(0,
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
unique += 1
}
}
if chars.count > max.count {
max = word
} else if chars.count == max.count {
if word < max {
max = word
}
}
}
return max
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = ""
for word in words {
var unique = 0
var chars = [Character]()
for char in word {
if !chars.contains(char) {
chars.append(char)
unique += 1
}
}
if chars.count > max.count {
max = word
} else if chars.count == max.count {
if word < max {
max = word
}
}
}
return max
}
print(findMax(["name", "of", "string"]))
print(findMax(["name", "enam", "game"]))
print(findMax(["aaaaaaa", "bb", "cc"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn", "oooooo"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn", "oooooo", "pppppp"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn", "oooooo", "pppppp", "qqqqqq"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn", "oooooo", "pppppp", "qqqqqq", "rrrrrr"]))
print(findMax(["aaaaaaa", "bb", "cc", "ddddd", "eeeeee", "fffff", "gggggg", "hhhhhh", "iiiiii", "llllll", "mmmmmm", "nnnnnn", "oooooo", "pppppp", "qqqqqq", "rrrrrr", "ssssss"]))
print(findMax(["aaaaaaa", "bb"
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = max(0, need - eaten)
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = max(0, need - eaten)
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var left = remaining
while eaten < need {
eaten += left
left = 0
}
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var left = remaining
while eaten < need {
eaten += left
left = 0
}
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + need
let left = remaining - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + need
let left = remaining - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
func stringCases(input: String) -> String {
let words = input.split(separator: " ")
let reversed = words.reversed()
let joined = reversed.joined(separator: " ")
return joined.toUpperCase()
}
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
// 2.
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// Example:
// Input: "Example Input"
// Output: "iNPUT eXAMPLE"
// Input: "Example Input With Multiple Words"
// Output: "iNPUT wIth mUltIple wOrDS eXAMPLE INPUT"
// Constrain:
// * No loops, or arrays!
// Good luck!
// stringCases("Example Input") == "iNPUT eXAMPLE"
// stringCases("Example Input With Multiple Words") == "iNPUT wIth mUltIple wOrDS eXAMPLE INPUT"
func stringCases(input: String) -> String {
let words = input.split(separator: " ")
let reversed = words.reversed()
let joined = reversed.joined(separator: " ")
return joined.toUpperCase()
}
// 3.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
// map(function(x) { return x+x; })
// Constrain:
// * Do not use the built-in Array.prototype.map method.
// map(function(x) { return x+x; })
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// 4.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
// map(function(x) { return x+x; })
// Constrain:
// * Do not use the built-in Array.prototype.map method.
// map(function(x) { return x+x; })
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// 5.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
// map(function(x) { return x+x; })
// Constrain:
// * Do not use the built-in Array.prototype.map method.
// map(function(x) { return x+x; })
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// 6.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
// map(function(x) { return x+x; })
// Constrain:
// * Do not use the built-in Array.prototype.map method.
// map(function(x) { return x+x; })
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// 7.
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
// For the beginner, try to use the map method - it comes in very handy quite a lot so is a
return joined.toUpperCase() // value of type 'String' has no member 'toUpperCase'
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + remaining
let left = need - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + need
let left = remaining - eaten
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let eaten = number + need
let left = remaining - eaten
return [eaten, left]
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var left = remaining
while eaten < need {
eaten += left
left -= eaten - number
eaten = number
}
return [eaten, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var eaten = number
var left = remaining
while eaten < need {
eaten += left
left -= eaten - number
eaten = number
}
return [eaten, left]
}
// 2.
// Given a string, find the first character that is not repeated anywhere in the string.
// If there are no characters that are not repeated, return null (or return None for Python).
// (Do not mutate the string!)
// Ex.
// "abracadabra" => "c"
// "allottee" => "t"
// "zombie" => "e"
// "abracadabraaazz" => nil
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]] == 1) {
// return str[i]
// }
// }
// return null
// }
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]] == 1) {
// return str[i]
// }
// }
// return null
// }
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]] == 1) {
// return str[i]
// }
// }
// return null
// }
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]] == 1) {
// return str[i]
// }
// }
// return null
// }
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]] == 1) {
// return str[i]
// }
// }
// return null
// }
// function firstNonRepeatedChar(str) {
// var obj = {}
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i]]) {
// obj[str[i]]++
// } else {
// obj[str[i]] = 1
// }
// }
// for (var i = 0; i < str.length; i++) {
// if (obj[str[i
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return 0
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return 0
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// ---------------
result = result ** operands[i] // no operator '**' is defined; did you mean 'pow(_:_:)'?
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
//
result **= operands[i] // cannot find operator '**=' in scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "^":
result = result ** operands[i]
default:
return 0
}
}
return result
}
func lengthOfLongestSubstring(_ s: String) -> Int {
var result = 0
var left = 0
var right = 0
var hash = [Character: Int]()
while right < s.count {
if hash[s[right]] != nil {
left = max(left, hash[s[right]]! + 1)
}
hash[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "^":
result = result ** operands[i]
default:
return 0
}
}
return result
}
let operators = ["+", "*", "-"]
let operands = [2, 3, 4, 5]
print(doAlgebra(operators: operators, operands: operands))<|endoftext|>// Given a string s, find the length of the longest substring without repeating characters.
// Example 1:
// Input: s = "abcabcbb"
// Output: 3
// Explanation: The answer is "abc", with the length of 3.
// Example 2:
// Input: s = "bbbbb"
// Output: 1
// Explanation: The answer is "b", with the length of 1.
// Example 3:
// Input: s = "pwwkew"
// Output: 3
// Explanation: The answer is "wke", with the length of 3.
// Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
// Example 4:
// Input: s = ""
// Output: 0
// Constraints:
// 0 <= s.length <= 5 * 104
// s consists of English letters, digits, symbols and spaces.
// Solution 1
// Time complexity: O(n)
// Space complexity: O(n)
func lengthOfLongestSubstring(_ s: String) -> Int {
var result = 0
var left = 0
var right = 0
var hash = [Character: Int]()
while right < s.count {
if hash[s[right]] != nil {
left = max(left, hash[s[right]]! + 1)
}
hash[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
// Solution 2
// Time complexity: O(n)
// Space complexity: O(n)
func lengthOfLongestSubstring(_ s: String) -> Int {
var result = 0
var left = 0
var right = 0
var hash = [Character: Int]()
while right < s.count {
if hash[s[right]] != nil {
left = max(left, hash[s[right]]! + 1)
}
hash[s[right]] = right
result = max(result, right - left + 1)
right += 1
}
return result
}
let s = "abcabcbb"
print(lengthOfLongestSubstring(s))<|endoftext|>// Given a string s, return the longest palindromic substring in s.
// Example 1:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: s = "cbbd"
// Output: "bb"
// Example 3:
// Input: s = "a"
// Output: "a"
// Example 4:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
// Solution 1
// Time complexity: O(n^2)
// Space complexity: O(1)
func longestPalindrome(_ s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var left = i
var right = j
while left < right {
if s[left] != s[right] {
result = result ** operands[i] // no operator '**' is defined; did you mean 'pow(_:_:)'?
if hash[s[right]] != nil { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
left = max(left, hash[s[right]]! + 1) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
hash[s[right]] = right // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result = result + operands[i]
case "-":
result = result - operands[i]
case "*":
result = result * operands[i]
case "/":
result = result / operands[i]
case "^":
result = result ** operands[i]
default:
break
}
}
return result
}
func sumOfPositive(array: [Int]) -> Int {
var result = 0
for i in array {
if i > 0 {
result += i
}
}
return result
}
func differenceOfMaxAndMin(array: [Int]) -> Int {
var max = array[0]
var min = array[0]
for i in array {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
func containsThree(array: [Int]) -> Bool {
for i in array {
if i == 3 {
if array[i+1] == 3 {
return true
}
}
}
return false
}
func removeNine(array: [Int]) -> [Int] {
var result = []
for i in array {
if i != 9 {
result.append(i)
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result = result + operands[i]
case "-":
result = result - operands[i]
case "*":
result = result * operands[i]
case "/":
result = result / operands[i]
case "^":
result = result ** operands[i]
default:
break
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// 11. Given an array of integers, return the sum of all the positive integers in the array.
// Example:
// array = [1, 2, 3, 4, 5]
// result = 15
// Note:
// The length of the array will not exceed 100.
// All the integers in the array will be less than 1000.
func sumOfPositive(array: [Int]) -> Int {
var result = 0
for i in array {
if i > 0 {
result += i
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// 12. Given an array of integers, return the difference between the largest and smallest integers in the array.
// Example:
// array = [1, 2, 3, 4, 5]
// result = 4
// Note:
// The length of the array will not exceed 100.
// All the integers in the array will be less than 1000.
func differenceOfMaxAndMin(array: [Int]) -> Int {
var max = array[0]
var min = array[0]
for i in array {
if i > max {
max = i
}
if i < min {
min = i
}
}
return max - min
}
// -------------------------------------------------------------------------------------------------
// 13. Given an array of integers, return true if the array contains a 3 next to a 3 somewhere.
// Example:
// array = [1, 3, 3]
// result = true
// Note:
// The length of the array will not exceed 100.
// All the integers in the array will be less than 100.
func containsThree(array: [Int]) -> Bool {
for i in array {
if i == 3 {
if array[i+1] == 3 {
return true
}
}
}
return false
}
// -------------------------------------------------------------------------------------------------
// 14. Given an array of integers, return the array without any 9s, so [2, 5, 9] returns [2, 5].
// Example:
// array = [2, 5, 9]
// result = [2, 5]
// Note:
// The length of the array will not exceed 100.
// All the integers in the array will be less than 100.
func removeNine(array: [Int]) -> [Int] {
var result = []
for i in array {
if i != 9 {
result.append(i)
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// 15. Given an array of integers, return the array without any 9s, so [2, 5, 9] returns [2, 5].
// Example:
// array = [2, 5, 9]
// result = [2, 5]
// Note:
result = result ** operands[i] // no operator '**' is defined; did you mean 'pow(_:_:)'?
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
return 0
}
}
return result
}
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > result.count {
result = substring
}
}
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
return 0
}
}
return result
}
// 2.
// Given a string s, return the longest palindromic substring in s.
// Example:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: s = "cbbd"
// Output: "bb"
// Example:
// Input: s = "a"
// Output: "a"
// Example:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > result.count {
result = substring
}
}
}
}
return result
}
// 3.
// Given a string s, return the longest palindromic substring in s.
// Example:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: s = "cbbd"
// Output: "bb"
// Example:
// Input: s = "a"
// Output: "a"
// Example:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > result.count {
result = substring
}
}
}
}
return result
}
// 4.
// Given a string s, return the longest palindromic substring in s.
// Example:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: s = "cbbd"
// Output: "bb"
// Example:
// Input: s = "a"
// Output: "a"
// Example:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
func longestPalindrome(s: String) -> String {
var result = ""
for i in 0..<s.count {
for j in i..<s.count {
var substring = s[i..<j]
if substring == substring.reversed() {
if substring.count > result.count {
result = substring
}
}
}
}
return result
}
// 5.
// Given a string s, return the longest palindromic substring in s.
// Example:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example:
// Input: s = "cbbd"
// Output: "bb"
// Example:
// Input: s = "a"
// Output: "a"
result **= operands[i] // cannot find operator '**=' in scope
var substring = s[i..<j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if substring == substring.reversed() { // binary operator '==' cannot be applied to operands of type 'String' and '[String.Element]' (aka 'Array<Character>')
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
let operators = ["+", "*", "-"]
let operands = [2, 3, 4, 5]
print(doAlgebra(operators: operators, operands: operands))<|endoftext|>// Given a string s, return the longest palindromic substring in s.
// Example 1:
// Input: s = "babad"
// Output: "bab"
// Note: "aba" is also a valid answer.
// Example 2:
// Input: s = "cbbd"
// Output: "bb"
// Example 3:
// Input: s = "a"
// Output: "a"
// Example 4:
// Input: s = "ac"
// Output: "a"
// Constraints:
// 1 <= s.length <= 1000
// s consist of only digits and English letters.
// Solution 1:
// 1. Create a function that takes a string and returns the longest palindrome substring.
// 2. Create a function that takes a string and returns the longest palindrome substring.
// 3. Create a function that takes a string and returns the longest palindrome substring.
// 4. Create a function that takes a string and returns the longest palindrome substring.
// 5. Create a function that takes a string and returns the longest palindrome substring.
// 6. Create a function that takes a string and returns the longest palindrome substring.
// 7. Create a function that takes a string and returns the longest palindrome substring.
// 8. Create a function that takes a string and returns the longest palindrome substring.
// 9. Create a function that takes a string and returns the longest palindrome substring.
// 10. Create a function that takes a string and returns the longest palindrome substring.
// 11. Create a function that takes a string and returns the longest palindrome substring.
// 12. Create a function that takes a string and returns the longest palindrome substring.
// 13. Create a function that takes a string and returns the longest palindrome substring.
// 14. Create a function that takes a string and returns the longest palindrome substring.
// 15. Create a function that takes a string and returns the longest palindrome substring.
// 16. Create a function that takes a string and returns the longest palindrome substring.
// 17. Create a function that takes a string and returns the longest palindrome substring.
// 18. Create a function that takes a string and returns the longest palindrome substring.
// 19. Create a function that takes a string and returns the longest palindrome substring.
// 20. Create a function that takes a string and returns the longest palindrome substring.
// 21. Create a function that takes a string and returns the longest palindrome substring.
// 22. Create a function that takes a string and returns the longest palindrome substring.
// 23. Create a function that takes a string and returns the longest palindrome substring.
// 24. Create a function that takes a string and returns the longest palindrome substring.
// 25. Create a function that takes a string and returns the longest palindrome substring.
// 26. Create a function that takes a string and returns the longest palindrome substring.
// 27. Create a function that takes a string and returns the longest palindrome substring.
// 28. Create a function that takes a string and returns the longest palindrome substring.
// 29. Create a function that takes a string and returns the longest palindrome substring.
// 30. Create a function that takes a string and returns
result **= operands[i] // cannot find operator '**=' in scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
//
result **= operands[i] // cannot find operator '**=' in scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
//
result **= operands[i] // cannot find operator '**=' in scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
switch operators[i-1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "/":
result /= operands[i]
case "**":
result **= operands[i]
default:
break
}
}
return result
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// ---
result **= operands[i] // cannot find operator '**=' in scope
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
if operators[i-1] == "+" {
result += operands[i]
} else if operators[i-1] == "-" {
result -= operands[i]
} else if operators[i-1] == "*" {
result *= operands[i]
} else if operators[i-1] == "//" {
result /= operands[i]
} else if operators[i-1] == "**" {
result **= operands[i]
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
var result = operands[0]
for i in 1..<operands.count {
if operators[i-1] == "+" {
result += operands[i]
} else if operators[i-1] == "-" {
result -= operands[i]
} else if operators[i-1] == "*" {
result *= operands[i]
} else if operators[i-1] == "//" {
result /= operands[i]
} else if operators[i-1] == "**" {
result **= operands[i]
}
}
return result
}
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 12. Write a function that takes a string as input and returns the string reversed.
// Example:
// Given s = "hello", return "olleh".
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 13. Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
// If the last word does not exist, return 0.
// Note: A word is defined as a character sequence consists of non-space characters only.
// Example:
// Input: "Hello World"
// Output: 5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 14. Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
// If the last word does not exist, return 0.
// Note: A word is defined as a character sequence consists of non-space characters only.
// Example:
// Input: "Hello World"
// Output: 5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 15. Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
// If the last word does not exist, return 0.
// Note: A word is defined as a character sequence consists of non-space characters only.
// Example:
// Input: "Hello World"
// Output: 5
// ----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
// MARK: - 16. Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
// If the last word does not exist, return 0.
// Note: A word is defined as a character sequence consists of non-space characters only.
// Example:
// Input: "Hello World"
// Output: 5
// ----------------------------------------------------------------------------------------------------------------------
// ---
result **= operands[i] // cannot find operator '**=' in scope
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 10. Write a function that takes a string as an argument and returns a string
// with the first and the last character swapped.
// Examples
// swap("Hello") == "oelH"
// swap("goodbye") == "goodby"
// swap("q") == "q"
// swap("1234") == "4321"
// swap("12") == "21"
// swap("1") == "1"
// swap("") == ""
// swap("a") == "a"
// swap("aa") == "aa"
// swap("z") == "z"
// swap("12345") == "54321"
// swap("123456789") == "987654321"
// swap("abcdefghijklmnopqrstuvwxyz") == "zyxwvutsrqponmlkjihgfedcba"
// swap("ABCDEFGHIJKLMNOPQRSTUVWXYZ") == "ZYXWVUTSRQPONMLKJIHGFEDCBA"
// swap("1234567890") == "9087654321"
// swap("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// swap("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
// swap("!@#$%^&*()_+") == "!@#$%^&*()_+"
// swap("1234567890!@#$%^&*()_+") == "!@#$%^&*()_+2345678901"
// swap("abcdefghijklmnopqrstuvwxyz!@#$%^&*()_+") == "!@#$%^&*()_+zyxwvutsrqponmlkjihgfedcba"
// swap("ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+") == "!@#$%^&*()_+ZYXWVUTSRQPONMLKJIHGFEDCBA"
// swap("1234567890!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// swap("!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
// swap("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+")
// swap("1234567890!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// swap("!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
// swap("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+")
// swap("1234567890!@#$%^&*()_+abcdefghijklmnopqrstuvwxyzABC
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
func solve(s: String) -> Int {
var result = 0
var start = 0
var map = [Character: Int]()
for i in 0..<s.count {
if map.containsKey(s[i]) {
start = max(start, map[s[i]] + 1)
}
map[s[i]] = i
result = max(result, i - start + 1)
}
return result
}
func solve(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var map = [Int: Int]()
for i in 0..<nums.count {
if map.contains(key: target - nums[i]) {
result = [map[target - nums[i]], i]
}
map[nums[i]] = i
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// 2.
// Given a string s, find the length of the longest substring without repeating characters.
// Examples
// solve(s: "abcabcbb") == 3
// solve(s: "bbbbb") == 1
// solve(s: "pwwkew") == 3
func solve(s: String) -> Int {
var result = 0
var start = 0
var map = [Character: Int]()
for i in 0..<s.count {
if map.containsKey(s[i]) {
start = max(start, map[s[i]] + 1)
}
map[s[i]] = i
result = max(result, i - start + 1)
}
return result
}
// 3.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Examples
// solve(nums: [2, 7, 11, 15], target: 9) == [0, 1]
// solve(nums: [3, 2, 4], target: 6) == [1, 2]
// solve(nums: [3, 3], target: 6) == [0, 1]
func solve(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var map = [Int: Int]()
for i in 0..<nums.count {
if map.contains(key: target - nums[i]) {
result = [map[target - nums[i]], i]
}
map[nums[i]] = i
}
return result
}
// 4.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Examples
// solve(nums: [2, 7, 11, 15], target: 9) == [0, 1]
// solve(nums: [3, 2, 4], target: 6) == [1, 2]
// solve(nums: [3, 3], target: 6) == [0, 1]
func solve(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var map = [Int: Int]()
for i in 0..<nums.count {
if map.contains(key: target - nums[i]) {
result = [map[target - nums[i]], i]
}
map[nums[i]] = i
}
return result
}
// 5.
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
// Examples
// solve(nums: [2, 7, 11, 15], target: 9) == [0, 1]
// solve(nums: [3, 2, 4], target: 6) == [1, 2]
// solve(nums: [3, 3], target: 6) == [0, 1]
func solve(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var map = [Int: Int]()
for i in
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if map.containsKey(s[i]) { // value of type '[Character : Int]' has no member 'containsKey'
start = max(start, map[s[i]] + 1) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
map[s[i]] = i // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if map.contains(key: target - nums[i]) { // incorrect argument label in call (have 'key:', expected 'where:')
result = [map[target - nums[i]], i] // cannot convert value of type 'Int?' to expected element type 'Array<Int>.ArrayLiteralElement' (aka 'Int')
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// 2.
// Given a string, find the first character that is not repeated in the string.
// Examples
// firstNotRepeatedCharacter("abcdcaf") == "b"
// firstNotRepeatedCharacter("abcd") == "e"
// firstNotRepeatedCharacter("") == ""
// firstNotRepeatedCharacter("aabbccddeef") == "f"
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyz") == "a"
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba") == "a"
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyza")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzab")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabc")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefg")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghij")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmno")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnop")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopq")
// firstNotRepeatedCharacter("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqr")
// firstNotRepeatedCharacter("abcdef
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char.isLower {
result += char.upperCased
} else {
result += char.lowerCased
}
}
return result
}
func toLower(s: String) -> String {
var result = ""
for char in s {
result += char.lowerCased
}
return result
}
func toUpper(s: String) -> String {
var result = ""
for char in s {
result += char.upperCased
}
return result
}
func toNumbers(s: String) -> String {
var result = ""
for char in s {
result += String(char.unicode.value)
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 2.
// Write a function that takes a string as input and returns the string reversed.
// Examples
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("h") == "h"
// reverse("aab") == "bba"
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// -----------------------------------------------------------------------------
// 3.
// Write a function that takes a string as input and returns the string with all
// the capital letters converted to lowercase and vice versa.
// Examples
// swapCase("Hello, World!") == "hELLO, wORLD!"
// swapCase("HELLO, WORLD!") == "hello, world!"
// swapCase("") == ""
// swapCase("12345") == "12345"
func swapCase(s: String) -> String {
var result = ""
for char in s {
if char.isLower {
result += char.upperCased
} else {
result += char.lowerCased
}
}
return result
}
// -----------------------------------------------------------------------------
// 4.
// Write a function that takes a string as input and returns the string with
// all the letters converted to lowercase.
// Examples
// toLower("Hello, World!") == "hello, world!"
// toLower("HELLO, WORLD!") == "hello, world!"
// toLower("") == ""
// toLower("12345") == "12345"
func toLower(s: String) -> String {
var result = ""
for char in s {
result += char.lowerCased
}
return result
}
// -----------------------------------------------------------------------------
// 5.
// Write a function that takes a string as input and returns the string with all
// the letters converted to uppercase.
// Examples
// toUpper("Hello, World!") == "HELLO, WORLD!"
// toUpper("HELLO, WORLD!") == "HELLO, WORLD!"
// toUpper("") == ""
// toUpper("12345") == "12345"
func toUpper(s: String) -> String {
var result = ""
for char in s {
result += char.upperCased
}
return result
}
// -----------------------------------------------------------------------------
// 6.
// Write a function that takes a string as input and returns the string with all
// the letters replaced by their corresponding numbers.
// Examples
// toNumbers("hello") == "111222333"
// toNumbers("") == ""
// toNumbers("12345") == "12345"
func toNumbers(s: String) -> String {
var result = ""
for char in s {
result += String(char.unicode.value)
}
return result
}
// -----------------------------------------------------------------------------
// 7.
// Write a function that takes a string as input and returns the string with all
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lowerCased // value of type 'Character' has no member 'lowerCased'
result += char.upperCased // value of type 'Character' has no member 'upperCased'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.upperCased // value of type 'Character' has no member 'upperCased'
result += char.lowerCased // value of type 'Character' has no member 'lowerCased'
result += char.lowerCased // value of type 'Character' has no member 'lowerCased'
result += char.upperCased // value of type 'Character' has no member 'upperCased'
result += String(char.unicode.value) // value of type 'Character' has no member 'unicode'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number.length > 0 {
result += Int(number)!
number = ""
}
}
}
if number.length > 0 {
result += Int(number)!
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.10
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number.length > 0 {
result += Int(number)!
number = ""
}
}
}
if number.length > 0 {
result += Int(number)!
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.11
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number.length > 0 {
result += Int(number)!
number = ""
}
}
}
if number.length > 0 {
result += Int(number)!
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.12
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number.length > 0 {
result += Int(number)!
number = ""
}
}
}
if number.length > 0 {
result += Int(number)!
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.13
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lowerCased // value of type 'Character' has no member 'lowerCased'
result += char.upperCased // value of type 'Character' has no member 'upperCased'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
number += char // cannot convert value of type 'Character' to expected argument type 'String'
if number.length > 0 { // value of type 'String' has no member 'length'
if number.length > 0 { // value of type 'String' has no member 'length'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
func join(a: String) -> String {
return "something " + a
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 12. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 13. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 14. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 15. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 16. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 17. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 18. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
// Examples
// join("is better than nothing") == "something is better than nothing"
// join("is better than nothing at all") == "something is better than nothing at all"
func join(a: String) -> String {
return "something " + a
}
// -----------------------------------------------------------------------------
// 19. Write a function that returns the string "something" joined with a space
// " " and the given argument a.
//
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
func swap(s: String) -> String {
var result = ""
for char in s {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number != "" {
result += Int(number)
number = ""
}
}
}
if number != "" {
result += Int(number)
}
return result
}
func stringTransformer(s: String) -> String {
var result = ""
var word = ""
for char in s {
if char == " " {
result = word + " " + result
word = ""
} else {
word += char
}
}
if word != "" {
result = word + " " + result
}
return result
}
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// Task
// Given a string, swap the case of each character.
// For example, if you get "Hello World" as input, you should return "hELLO wORLD".
// Examples
// swap("Hello World") == "hELLO wORLD"
// swap("cODING") == "CODING"
// swap("12345") == "12345"
// swap("abcdefg") == "ABCDEFg"
func swap(s: String) -> String {
var result = ""
for char in s {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
}
return result
}
// Task
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// For example, if the string is "abc123xyz", the function should return 123.
// If there are no numbers in the string, the function should return 0.
// Ignore all characters that are not a digit char.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5one") == 0
func sumNumbers(s: String) -> Int {
var result = 0
var number = ""
for char in s {
if char.isDigit {
number += char
} else {
if number != "" {
result += Int(number)
number = ""
}
}
}
if number != "" {
result += Int(number)
}
return result
}
// Task
// Given a string, return a new string that has transformed based on the input:
// Change case of every character, ie. lower case to upper case, upper case to lower case.
// Reverse the order of words from the input.
// Note: You will have to handle multiple spaces, and leading/trailing spaces.
// For example:
// "Example Input" ==> "iNPUT eXAMPLE"
// You may assume the input only contain English alphabet and spaces.
// Examples
// stringTransformer("Example Input") == "iNPUT eXAMPLE"
// stringTransformer("Input Example") == "iNPUT eXAMPLE"
// stringTransformer(" Input Example ") == " iNPUT eXAMPLE "
// stringTransformer("input example") == "iNPUT eXAMPLE"
// stringTransformer("iNPUT eXAMPLE") == "iNPUT eXAMPLE"
func stringTransformer(s: String) -> String {
var result = ""
var word = ""
for char in s {
if char == " " {
result = word + " " + result
word = ""
} else {
word += char
}
}
if word != "" {
result = word + " " + result
}
return result
}
// Task
// Given a string, return a new string with the reversed order of characters.
// Examples
// reverse("apple") == "elppa"
// reverse("hello") == "olleh"
// reverse("Greetings!") == "!sgniteerG"
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// Task
// Given a string, you have to return a
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
number += char // cannot convert value of type 'Character' to expected argument type 'String'
result += Int(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += Int(number) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
word += char // cannot convert value of type 'Character' to expected argument type 'String'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 10.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// If there is no number in the string, return 0.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5hoco1a12") == 5
// sumNumbers("") == 0
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
// -----------------------------------------------------------------------------
// 11.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// If there is no number in the string, return 0.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5hoco1a12") == 5
// sumNumbers("") == 0
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber)
currentNumber = ""
}
}
}
if currentNumber != "" {
result += Int(currentNumber)
}
return result
}
// -----------------------------------------------------------------------------
// 12.
// Given a string, return the sum of the numbers appearing in the string, ignoring all other characters.
// A number is a series of 1 or more digit chars in a row.
// A non-number is any char that is not a digit.
// If there is no number in the string, return 0.
// Examples
// sumNumbers("abc123xyz") == 123
// sumNumbers("aa11b33") == 44
// sumNumbers("7 11") == 18
// sumNumbers("Chocolate") == 0
// sumNumbers("5hoco1a12") == 5
// sumNumbers("") == 0
func sumNumbers(s: String) -> Int {
var result = 0
var currentNumber = ""
for char in s {
if char.isDigit {
currentNumber += char
} else {
if currentNumber != "" {
result += Int(currentNumber
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
if char.isDigit { // value of type 'Character' has no member 'isDigit'
currentNumber += char // cannot convert value of type 'Character' to expected argument type 'String'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
result += Int(currentNumber) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isLower {
result += char.uppercaseString
} else {
result += char.lowercaseString
}
} else {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// Examples
// solve(s: "abracadabra") == "brckdrb"
// solve(s: "pear tree") == "pqr tree"
// solve(s: "o a kak ushakov lil vo kashu kakao") == "ck sv ks csv sks csv"
// solve(s: "my pyx") == "m y kx"
// solve(s: "hieeelalaooo") == "hello"
// solve(s: "one") == "one"
// solve(s: "neo") == "neo"
// solve(s: "helLo") == "hll"
// solve(s: "heLlO") == "hll"
// solve(s: "my name is") == "m y nms n"
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// Examples
// solve(s: "abracadabra") == "brckdrb"
// solve(s: "pear tree") == "pqr tree"
// solve(s: "o a kak ushakov lil vo kashu kakao") == "ck sv ks csv sks csv"
// solve(s: "my pyx") == "m y kx"
// solve(s: "hieeelalaooo") == "hello"
// solve(s: "one") == "one"
// solve(s: "neo") == "neo"
// solve(s: "helLo") == "hll"
// solve(s: "heLlO") == "hll"
// solve(s: "my name is") == "m y nms n"
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// Examples
// solve(s: "abracadabra") == "brckdrb"
// solve(s: "pear tree") == "pqr tree"
// solve(s: "o a kak ushakov lil vo kashu kakao") == "ck sv ks csv sks csv"
// solve(s: "my pyx") == "m y kx"
// solve(s: "hieeelalaooo") == "hello"
// solve(s: "one") == "one"
// solve(s: "neo") == "neo"
// solve(s: "helLo") == "hll"
// solve(s: "heLlO") == "hll"
// solve(s: "my name is") == "m y nms n"
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string as an argument and returns a new string
// with all the vowels removed.
// Examples
// solve(s: "abracadabra") == "brckdrb"
// solve(s: "pear tree") == "pqr tree"
// solve(s: "o a kak ushakov lil vo kashu kakao") == "ck sv ks csv sks csv"
// solve(s: "my pyx") == "m y kx"
// solve(s:
if char.isLower { // value of type 'Character' has no member 'isLower'
result += char.uppercaseString // value of type 'Character' has no member 'uppercaseString'
result += char.lowercaseString // value of type 'Character' has no member 'lowercaseString'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
func swap(s: String) -> String {
if s.isEmpty {
return ""
}
return s.last + s[1..<s.count - 1] + s[0]
}
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if !char.isVowel {
result += char
}
}
return result
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
if char.isUpper {
result += char.lowerCased
} else {
result += char.upperCased
}
} else {
result += char
}
}
return result
}
// 2.
// Write a function that takes a string as input and returns the string reversed.
// Examples
// reverse("hello") == "olleh"
// reverse("") == ""
// reverse("12345") == "54321"
func reverse(s: String) -> String {
var result = ""
for char in s {
result = char + result
}
return result
}
// 3.
// Write a function that takes a string as input and returns the string with the first
// and the last characters swapped.
// Examples
// swap("Hello") == "oHell"
// swap("goodbye") == "goodby"
// swap("") == ""
// swap("1") == "1"
func swap(s: String) -> String {
if s.isEmpty {
return ""
}
return s.last + s[1..<s.count - 1] + s[0]
}
// 4.
// Write a function that takes a string as input and returns the string with all the
// vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("") == ""
// removeVowels("a") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if !char.isVowel {
result += char
}
}
return result
}
// 5.
// Write a function that takes a string as input and returns the string with all the
// vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("") == ""
// removeVowels("a") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if !char.isVowel {
result += char
}
}
return result
}
// 6.
// Write a function that takes a string as input and returns the string with all the
// vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("") == ""
// removeVowels("a") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if !char.isVowel {
result += char
}
}
return result
}
// 7.
// Write a function that takes a string as input and returns the string with all the
// vowels removed.
// Examples
// removeVowels("I have never seen a thin person drinking Diet Coke.") == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbr"
// removeVowels("") == ""
// removeVowels("a") == ""
func removeVowels(s: String) -> String {
var result = ""
for char in s {
if char.isUpper { // value of type 'Character' has no member 'isUpper'
result += char.lowerCased // value of type 'Character' has no member 'lowerCased'
result += char.upperCased // value of type 'Character' has no member 'upperCased'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
result = char + result // cannot convert value of type 'Character' to expected argument type 'String'
return s.last + s[1..<s.count - 1] + s[0] // cannot convert value of type 'Character' to expected argument type 'String'
return s.last + s[1..<s.count - 1] + s[0] // cannot convert value of type 'String.Element?' (aka 'Optional<Character>') to expected argument type 'String'
if !char.isVowel { // value of type 'Character' has no member 'isVowel'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text == "" {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(Encoding.utf8))
return data?.md5()?.description
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text == "" {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(Encoding.utf8))
return data?.md5()?.description
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(Encoding.utf8)) // value of type 'String' has no member 'lengthOfBytesUsingEncoding'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(Encoding.utf8)) // cannot convert value of type 'String.UTF8View' to expected argument type 'UnsafeRawPointer?'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(Encoding.utf8)) // cannot find 'Encoding' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8))
return data.md5().description
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8))
return data.md5().description
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // cannot convert value of type 'String.UTF8View' to expected argument type 'UnsafeRawPointer?'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // value of type 'String' has no member 'lengthOfBytesUsingEncoding'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // cannot infer contextual base in reference to member 'utf8'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(text).hexString()
}
func stringToSha256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA256.hash(text).hexString()
}
func stringToSha512(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA512.hash(text).hexString()
}
func stringToSha1(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA1.hash(text).hexString()
}
func stringToSha3_224(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_224.hash(text).hexString()
}
func stringToSha3_256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_256.hash(text).hexString()
}
func stringToSha3_384(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_384.hash(text).hexString()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(text).hexString()
}
// Given a string 'text', return its sha256 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha256(text: "Hello world") == "42b602938232a50487a317685882c7b944064037108642262642620023742656"
func stringToSha256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA256.hash(text).hexString()
}
// Given a string 'text', return its sha512 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha512(text: "Hello world") == "6312c7755b5526671822267884943a57052681743712070822593448523067664510736960863444270073"
func stringToSha512(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA512.hash(text).hexString()
}
// Given a string 'text', return its sha1 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha1(text: "Hello world") == "2a3521940069287997382c054492059400b6628d"
func stringToSha1(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA1.hash(text).hexString()
}
// Given a string 'text', return its sha3_224 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_224(text: "Hello world") == "0576786400244a116500221662064984"
func stringToSha3_224(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_224.hash(text).hexString()
}
// Given a string 'text', return its sha3_256 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_256(text: "Hello world") == "00906514009588711616061723485737"
func stringToSha3_256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_256.hash(text).hexString()
}
// Given a string 'text', return its sha3_384 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_384(text: "Hello world") == "00881420090080205930235824262512"
func stringToSha3_384(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_384.hash(text).hexString()
}
// Given a string 'text', return its sha3_512 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_512(text: "Hello world") == "00891510009
return MD5.hash(text).hexString() // cannot find 'MD5' in scope
return SHA256.hash(text).hexString() // cannot find 'SHA256' in scope
return SHA512.hash(text).hexString() // cannot find 'SHA512' in scope
return SHA1.hash(text).hexString() // cannot find 'SHA1' in scope
return SHA3_224.hash(text).hexString() // cannot find 'SHA3_224' in scope
return SHA3_256.hash(text).hexString() // cannot find 'SHA3_256' in scope
return SHA3_384.hash(text).hexString() // cannot find 'SHA3_384' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
let data = NSData(bytes: text.utf8, length: text.length)
let hash = data!.md5()
return String(bytes: hash, encoding: .utf8)
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
let data = NSData(bytes: text.utf8, length: text.length)
let hash = data!.md5()
return String(bytes: hash, encoding: .utf8)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------
let data = NSData(bytes: text.utf8, length: text.length) // value of type 'String' has no member 'length'
let data = NSData(bytes: text.utf8, length: text.length) // cannot convert value of type 'String.UTF8View' to expected argument type 'UnsafeRawPointer?'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(utf8String: text)
let hash = data!.md5()
return hash.hexEncodedString(uppercase: true)
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(utf8String: text)
let hash = data!.md5()
return hash.hexEncodedString(uppercase: true)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
let data = NSData(utf8String: text) // no exact matches in call to initializer
import CommonCrypto
func stringToMd5(text: String) -> String? {
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
let hash = crypto::md5(data)
return String(data: hash)
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
let hash = crypto::md5(data)
return String(data: hash)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------
let data = text.dataUsingEncoding(NSUTF8StringEncoding) // value of type 'String' has no member 'dataUsingEncoding'
let hash = crypto::md5(data) // expected expression
let hash = crypto::md5(data) // consecutive statements on a line must be separated by ';'
let hash = crypto::md5(data) // cannot find 'crypto' in scope
return String(data: hash) // missing argument for parameter 'encoding' in call
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(data: text.utf8).hexString()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(data: text.utf8).hexString()
}
// Example
// stringToMd5("Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
// Solution
// 1. Create a new string with the same length as the input string.
// 2. Iterate over each character in the input string.
// 3. For each character, convert it to its corresponding hexadecimal value.
// 4. Append the hexadecimal value to the new string.
// 5. Return the new string.
// Time Complexity: O(n)
// Space Complexity: O(1)
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------------------------------------------------------------
return MD5.hash(data: text.utf8).hexString() // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(utf8String: text)
let hash = data!.md5()
return String(bytes: hash, encoding: .utf8)
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = NSData(utf8String: text)
let hash = data!.md5()
return String(bytes: hash, encoding: .utf8)
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
let data = NSData(utf8String: text) // no exact matches in call to initializer
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text == "" {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8))
return data!.md5()!
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text == "" {
return nil
}
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8))
return data!.md5()!
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ---------------------
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // cannot convert value of type 'String.UTF8View' to expected argument type 'UnsafeRawPointer?'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // value of type 'String' has no member 'lengthOfBytesUsingEncoding'
let data = NSData(bytes: text.utf8, length: text.lengthOfBytesUsingEncoding(.utf8)) // cannot infer contextual base in reference to member 'utf8'
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(text).hexString()
}
func stringToSha256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA256.hash(text).hexString()
}
func stringToSha512(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA512.hash(text).hexString()
}
func stringToSha1(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA1.hash(text).hexString()
}
func stringToSha3_224(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_224.hash(text).hexString()
}
func stringToSha3_256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_256.hash(text).hexString()
}
func stringToSha3_384(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_384.hash(text).hexString()
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
return MD5.hash(text).hexString()
}
// Given a string 'text', return its sha256 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha256(text: "Hello world") == "098f6bcd4621d373cade4e832627b4f695f26f9598f39ae1a85a44a061174554"
func stringToSha256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA256.hash(text).hexString()
}
// Given a string 'text', return its sha512 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha512(text: "Hello world") == "d41d8cd98f00b204e9800998ecf8427e1"
func stringToSha512(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA512.hash(text).hexString()
}
// Given a string 'text', return its sha1 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha1(text: "Hello world") == "a94a8fe5ccb19ba61c41888da186449e077f8073"
func stringToSha1(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA1.hash(text).hexString()
}
// Given a string 'text', return its sha3_224 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_224(text: "Hello world") == "2232b268058d622d3c9b79346780c59a9465a095"
func stringToSha3_224(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_224.hash(text).hexString()
}
// Given a string 'text', return its sha3_256 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_256(text: "Hello world") == "d1c4639f99b168b4004a5a2b64692687231a8085"
func stringToSha3_256(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_256.hash(text).hexString()
}
// Given a string 'text', return its sha3_384 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_384(text: "Hello world") == "187584550784460386546676874883621099361"
func stringToSha3_384(text: String) -> String? {
if text.isEmpty {
return nil
}
return SHA3_384.hash(text).hexString()
}
// Given a string 'text', return its sha3_512 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToSha3_512(text: "Hello world") == "5f4dcc3b5aa765d61d8327deb882cf99e00b0059"
func stringToSha3_512(text: String)
return MD5.hash(text).hexString() // cannot find 'MD5' in scope
return SHA256.hash(text).hexString() // cannot find 'SHA256' in scope
return SHA512.hash(text).hexString() // cannot find 'SHA512' in scope
return SHA1.hash(text).hexString() // cannot find 'SHA1' in scope
return SHA3_224.hash(text).hexString() // cannot find 'SHA3_224' in scope
return SHA3_256.hash(text).hexString() // cannot find 'SHA3_256' in scope
return SHA3_384.hash(text).hexString() // cannot find 'SHA3_384' in scope
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 3. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 4. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Write a function that takes a string and returns a new string with all
// the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.") ==
// " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrdbrkr"
// removeVowels("") == ""
func removeVowels(input: String) -> String {
var result = ""
for char in input {
if char != "a" && char != "e" && char != "i" && char != "o" && char != "u" {
result += char
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Write a function that takes a string and returns a new string with all
// the vowels removed.
//
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
result += char // cannot convert value of type 'Character' to expected argument type 'String'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 3. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 4. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 5. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 6. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 7. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 8. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 9. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 10. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// ------------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a string, return a new string with all the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrd"
// removeVowels("pear tree") == " prtr"
// removeVowels("ho ho ho") == "h h h"
// removeVowels("hello world!") == "hll wrld!"
// removeVowels("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 3. Given a string, return a new string with all the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrd"
// removeVowels("pear tree") == " prtr"
// removeVowels("ho ho ho") == "h h h"
// removeVowels("hello world!") == "hll wrld!"
// removeVowels("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 4. Given a string, return a new string with all the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrd"
// removeVowels("pear tree") == " prtr"
// removeVowels("ho ho ho") == "h h h"
// removeVowels("hello world!") == "hll wrld!"
// removeVowels("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 5. Given a string, return a new string with all the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt Ck."
// removeVowels("abracadabra") == "brcrd"
// removeVowels("pear tree") == " prtr"
// removeVowels("ho ho ho") == "h h h"
// removeVowels("hello world!") == "hll wrld!"
// removeVowels("") == ""
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// 6. Given a string, return a new string with all the vowels removed.
// For example:
// removeVowels("I have never seen a thin person drinking Diet Coke.")
// == " hv nvr sn thn prsn drnkng Dt C
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func reverse(s: String) -> String {
var result = ""
for i in s.reversed() {
result += i
}
return result
}
func sameFirstAndLast(input: [Int]) -> Bool {
return input[0] == input[input.count - 1]
}
func doubleArray(input: [Int]) -> [Int] {
var result = []
for i in input {
result.append(i * 2)
}
return result
}
func removeVowels(s: String) -> String {
var result = ""
for i in s {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
result += i
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a string, return a new string with the reversed order of characters.
// For example:
// reverse("hello") == "olleh"
// reverse("Howdy") == "ydwoH"
// reverse("Greetings!") == "!sgniteerG"
func reverse(s: String) -> String {
var result = ""
for i in s.reversed() {
result += i
}
return result
}
// -----------------------------------------------------------------------------
// 3. Given a string, return true if the first and last numbers are the same;
// otherwise, return false.
// For example:
// sameFirstAndLast([1, 2, 3]) == false
// sameFirstAndLast([1, 2, 3, 1]) == true
// sameFirstAndLast([7, 7, 7]) == true
func sameFirstAndLast(input: [Int]) -> Bool {
return input[0] == input[input.count - 1]
}
// -----------------------------------------------------------------------------
// 4. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(input: [Int]) -> [Int] {
var result = []
for i in input {
result.append(i * 2)
}
return result
}
// -----------------------------------------------------------------------------
// 5. Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(input: [Int]) -> [Int] {
var result = []
for i in input {
result.append(i * 2)
}
return result
}
// -----------------------------------------------------------------------------
// 6. Given a string, return a new string with all the vowels removed.
// For example:
// "Hello" --> "Hll"
// "Good job!" --> "Gd jb!"
// "Skip to the end!" --> "St t st!"
// "aeiou" --> "" (with a string of consecutive vowels, like "aeiouaeiou")
// "aeiouaeiouaeiouaeiou" --> ""
func removeVowels(s: String) -> String {
var result = ""
for i in s {
if i != "a" && i != "e" && i != "i" && i != "o" && i != "u" {
result += i
}
}
return result
}
// -----------------------------------------------------------------------------
// 7. Given a string, return true if the first and last numbers are the same;
// otherwise, return false.
// For example:
// sameFirstAndLast([1, 2, 3]) == false
// sameFirstAndLast([1, 2, 3, 1]) == true
// sameFirstAndLast([7, 7, 7]) == true
func sameFirstAndLast(input: [Int]) -> Bool {
return input[0] == input[input.count - 1]
}
// -----------------------------------------------------------------------------
// 8. Given an array of
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
result += i // cannot convert value of type 'Character' to expected argument type 'String'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in (a...b) {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 1.1.1
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.2
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.3
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.4
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.5
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.6
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.7
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.8
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4, 6]
func doubleArray(array: [Int]) -> [Int] {
return array.map { $0 * 2 }
}
// -----------------------------------------------------------------------------
// 1.1.9
// Given an array of integers, return a new array with each value doubled.
// For example:
// [1, 2, 3] --> [2, 4
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// ------------
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
func reverse(s: String) -> String {
var result = ""
for i in s.reversed() {
result += i
}
return result
}
func isPalindrome(s: String) -> Bool {
return s == reverse(s: s)
}
func countChar(s: String, c: String) -> Int {
var result = 0
for i in s {
if i == c {
result += 1
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = []
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
// -----------------------------------------------------------------------------
// 2. Given a string, return a new string with the reversed order of characters.
// For example:
// reverse("hello") == "olleh"
// reverse("Greetings!") == "!sgniteerG"
func reverse(s: String) -> String {
var result = ""
for i in s.reversed() {
result += i
}
return result
}
// -----------------------------------------------------------------------------
// 3. Given a string, return true if the string is a palindrome.
// A palindrome is a word that is spelled the same forwards and backwards.
// For example:
// isPalindrome("noon") == true
// isPalindrome("racecar") == true
// isPalindrome("hello") == false
func isPalindrome(s: String) -> Bool {
return s == reverse(s: s)
}
// -----------------------------------------------------------------------------
// 4. Given a string, return the number of times the character appears in the
// string.
// For example:
// countChar("Hello", "l") == 2
// countChar("Hello", "e") == 1
// countChar("Hello", "z") == 0
func countChar(s: String, c: String) -> Int {
var result = 0
for i in s {
if i == c {
result += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 5. Given a string, return the number of times the character appears in the
// string.
// For example:
// countChar("Hello", "l") == 2
// countChar("Hello", "e") == 1
// countChar("Hello", "z") == 0
func countChar(s: String, c: String) -> Int {
var result = 0
for i in s {
if i == c {
result += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 6. Given a string, return the number of times the character appears in the
// string.
// For example:
// countChar("Hello", "l") == 2
// countChar("Hello", "e") == 1
// countChar("Hello", "z") == 0
func countChar(s: String, c: String) -> Int {
var result = 0
for i in s {
if i == c {
result += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 7. Given a string, return the number of times the character appears in the
// string.
// For example:
// countChar("Hello", "l") == 2
// countChar("Hello", "e") == 1
// countChar("Hello", "z") == 0
func countChar(s: String, c: String) -> Int {
var result = 0
for i in s {
if i == c {
result += 1
}
}
return result
}
// -----------------------------------------------------------------------------
// 8. Given a string, return the number of times the character appears in the
// string.
// For example:
//
var result = [] // empty collection literal requires an explicit type
return result // cannot convert return expression of type '[Any]' to return type '[Int]'
result += i // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
if i == c { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'